c# - 如何正确使用 EF 导航属性?

标签 c# asp.net linq entity-framework ef-code-first

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

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

我不知道我的类(class)是否正确设置来执行此操作。

  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; }

}

最佳答案

怎么样

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

var brands = context.Products.
    Where(p => p.Category.CategoryID == categoryToFind).
    Select(p => p.Brand.BrandName).Distinct().ToList();

如果您只需要品牌名称。

关于c# - 如何正确使用 EF 导航属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15075286/

相关文章:

c# - 是否可以在类中定义任何类型的列表,它可以包含任何类型的列表

c# - 如何仅发布 MVC 列表中选定的项目

asp.net - Internet Explorer 11 在 PageRequestManager.js 中出现脚本错误

c# - 如何将多个进度 div 添加到基于 List<T> 对象项的 div

linq - 在C#中使用Linq进行字符串替换

c# - 如何编写用于 Elasticsearch 匹配和模糊查询的 LINQ 表达式(NEST)

c# - 使用 CryptoAPI 在 Store C# 中通过哈希查找证书

javascript - 如何清除容器控件中的所有值

linq - Task.WhenAll 何时枚举?

c# - 是否有用于获取字符串列表中最长字符串的 LINQ 函数?