下面是我首先使用实体框架代码设置的 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/