【问题标题】:How to access many-to-many table via Entity Framework? asp.net如何通过实体框架访问多对多表?网
【发布时间】:2016-03-08 03:57:17
【问题描述】:

如何通过 EF 读取多对多表?我不知道如何使用多对多表。假设Product_Category 得到ProductIDCategoryID

我如何通过例如访问它

using(Entities db = new Entities)
{
    /* cant access these here.. */}

方法??但是我可以联系到Product_Category,但无法访问它的ProductIDCategoryID

我想列出每个产品,例如Product_Category.CategoryID == Category.ID.

我以前从未使用过多对多表,因此我很欣赏一些简单的示例,如何通过 asp.net 中的 EF 访问它们。

谢谢

【问题讨论】:

标签: c# sql asp.net entity-framework many-to-many


【解决方案1】:

导航属性是您的朋友。除非您在联结表中有其他属性,否则您不需要它。这就是您的模型中没有 Product_Category 的原因。所以说你的模型是:

public class Product
{
    public Product()
    {
        this.Categories = new HashSet<Category>();
    }
    public int ProductId { get; set; }
    public string ProductName { get; set; }

    public virtual ICollection<Category> Categories { get; set; }
}

public class Category
{
    public Category()
    {
        this.Products = new HashSet<Product>();
    }

    public int CategoryId { get; set; }
    public string CategoryName { get; set; }

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

所以现在,如果您想要一个类别中的所有产品,您可以执行以下操作:

var productsInCategory = db.Categorys
                      .Where(c => c.CategoryId == categoryId)
                      .SelectMany(c => c.Products);

如果您确实想要一个明确的联结表,请参阅:https://lostechies.com/jimmybogard/2014/03/12/avoid-many-to-many-mappings-in-orms/

【讨论】:

  • 谢谢,这正是我需要的!我想我必须做一些复杂的动作,比如添加另一个像 Product_Category 这样的类,结果一团糟。这比我想象的要容易得多。
【解决方案2】:

您必须将产品和类别表与桥表Product_Category 连接起来才能检索所需的产品信息。

using(eShopEntities db = new eShopEntities)
{
    var products = (from p in db.Product_Category 
                    join ProductTable pt on p.ID = pt.ProductID
                    join Category c on c.ID = P.CategoryID 
                    select new 
                           {
                                p.ID,
                                p.Name,
                                p.Description,
                                p.Price
                           }).ToList();
}

【讨论】:

  • 输入"var products = (from p in db."时如何访问Product_Category,Product_Category不会出现在列表中。当我添加桥表时,edmx设计只显示了一个新的产品和类别之间的关系为 m-2-m,但不会像其他表一样自动创建 Product_Category 类。是否必须手动创建 Product_Category 类?
  • 如果您的数据库中存在 Product_Category 表,那么它也应该显示在 edmx 设计中。
  • 我在 Product_Category 中添加了两个 ID 作为外键,没有任何主键,这导致这些表之间的多对多关系像“ [P-table] *----* [C-tabel]" 在 edmx 设计中,但没有显示 Product_Category 表。我做对了吗,还是我想也看到 Product_Category 表?
  • 不,这是由 EF 在幕后处理的。默认情况下,您没有用于联结表的 DbSet。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多