Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何正确使用导航属性?_C#_Asp.net_Linq_Entity Framework_Ef Code First - Fatal编程技术网

C# 如何正确使用导航属性?

C# 如何正确使用导航属性?,c#,asp.net,linq,entity-framework,ef-code-first,C#,Asp.net,Linq,Entity Framework,Ef Code First,下面是我首先使用实体框架代码设置的POCO类。如何查询数据库,以便返回特定类别的所有品牌 示例:您有一个类别列表,然后单击其中一个。它显示了该类别下可用的所有品牌的产品 我不知道我的课程设置是否正确 public class Product { [Key,ScaffoldColumn(false)] public int ProductID { get; set; } public string ProductName { get;

下面是我首先使用实体框架代码设置的POCO类。如何查询数据库,以便返回特定类别的所有品牌

示例:您有一个类别列表,然后单击其中一个。它显示了该类别下可用的所有品牌的产品

我不知道我的课程设置是否正确

  public class Product
    {
        [Key,ScaffoldColumn(false)]
        public int ProductID { get; set; }


        public string ProductName { get; set; }

        public int? CategoryID { get; set; }

        public virtual Category Category { get; set; }


        public int? BrandID { get; set; }

        public virtual Brand Brand { get; set; }


    }


   public class Brand
    {

        [ScaffoldColumn(false)]
        public int BrandID { get; set; }


        public string BrandName { get; set; }

    }


    public class Category
    {
        [ScaffoldColumn(false)]
        public int CategoryID { get; set; }

        public string CategoryName { get; set; }

        public virtual ICollection<Product> Products { get; set; }

}
公共类产品
{
[键,脚手架柱(假)]
public int ProductID{get;set;}
公共字符串ProductName{get;set;}
公共int?CategoryID{get;set;}
公共虚拟类别{get;set;}
公共int?BrandID{get;set;}
公共虚拟品牌{get;set;}
}
大众品牌
{
[脚手架立柱(假)]
public int BrandID{get;set;}
公共字符串BrandName{get;set;}
}
公共类类别
{
[脚手架立柱(假)]
public int CategoryID{get;set;}
公共字符串CategoryName{get;set;}
公共虚拟ICollection产品{get;set;}
}
那怎么办

context.Products.
    Where(p => p.Category.CategoryID == categoryToFind).Select(p => p.Brand);


如果您只需要品牌名称。

如果您需要类别中的所有品牌这样的信息,为什么不在
品牌
类别
之间建立关系呢。这么说来,我想你需要一个
1:N
M:N
关系,与这两个表/实体建立关系?我想了想,但我不认为品牌与类别有关系,而更重要的是与产品有关系。产品与类别和品牌都有关系。我想我想看看正确的方法是什么。我更喜欢外键关系,即使你只需要这个查询。否则,您必须使用
JOIN
和/或
UNION
LINQ
进行连接,我将尝试退出。外键场景更简单,我认为处理这个问题的方法更好。你能在一个片段中告诉我你的意思吗?我会试试。但是你能指定你需要的关系类型吗?1:N或M:N?如果您只想将
Brandnames
返回到页面,您会使用哪种类型的方法来包装它?IQueryable或List?@jackncoke可能是一个返回
Distinct()
名称列表的方法。如果没有太多的数据,甚至可以从客户端提取所有数据并在本地进行过滤。
var brands = context.Products.
    Where(p => p.Category.CategoryID == categoryToFind).
    Select(p => p.Brand.BrandName).Distinct().ToList();