如何通过实体框架访问多对多表? asp.net [英] How to access many-to-many table via Entity Framework? asp.net

查看:74
本文介绍了如何通过实体框架访问多对多表? asp.net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过EF读取多对多表格?我不知道如何使用多对多表.假设Product_Category在哪里得到ProductIDCategoryID.

How do I read a many-to-many table via EF? I have no idea how to use the many-to-many table. Let's say Product_Category where it got ProductID and CategoryID.

如何通过以下方式访问它:

How can I access it trough e.g.

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

方法??但是,我可以到达Product_Category,但无法访问其ProductIDCategoryID.

method?? I can however reach Product_Category, but cant access its ProductID or CategoryID.

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

I want to list every product e.g. where Product_Category.CategoryID == Category.ID.

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

I have never used many-to-many tables before, so I appreciate some simple examples how to access them trough EF in asp.net.

谢谢

推荐答案

导航属性是您的朋友.除非在联结表中具有其他属性,否则不需要它.这就是为什么您的模型中没有Product_Category的原因.假设您的模型是:

Navigation properties are your friend here. Unless you have other properties in the junction table, you don't need it. This is why there is no Product_Category in your models. So say your models are:

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

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

So now if you want all products in a category you can do something like:

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/

If you do want an explicit junction tables see this: https://lostechies.com/jimmybogard/2014/03/12/avoid-many-to-many-mappings-in-orms/

这篇关于如何通过实体框架访问多对多表? asp.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆