【问题标题】:How do i use navigation properties correctly EF?如何正确使用导航属性 EF?
【发布时间】:2013-02-25 19:53:07
【问题描述】:

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

}

【问题讨论】:

  • 如果您需要所有品牌类别的信息,为什么不创建BrandCategory 之间的关系。这么说我认为您需要1:NM:N 关系b/w 这两个表/实体?
  • 我想过这个问题,但我认为品牌与品类无关,而与产品更相关。产品与类别和品牌都有关系。我想我想看看正确的做法是什么。
  • 我更喜欢外键关系,即使你只需要这个查询。否则,您必须将JOIN 和/或UNIONLINQ 一起使用,我会尝试逃脱。外键场景更容易,我认为更好的方法来处理这个问题。
  • 你能告诉我你在 sn-p 中的意思吗?
  • 我会试试的。但是你能指定你需要的关系类型吗? 1:N 还是 M:N ?

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


【解决方案1】:

怎么样

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();

如果您只需要品牌名称。

【讨论】:

  • 如果您只想将Brandnames 返回到页面,您会将其包装在什么类型的方法中? IQueryable 还是 List?
  • @jackncoke 可能是一个返回Distinct() 名称列表的方法。如果没有太多数据,甚至可以将所有内容都拉到客户端并在本地过滤。
猜你喜欢
  • 2016-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
相关资源
最近更新 更多