【问题标题】:Retrieve related data in many to many relation with junction table using entity framework lambda expression使用实体框架 lambda 表达式检索与联结表的多对多关系中的相关数据
【发布时间】:2016-12-12 14:20:20
【问题描述】:

这是一个简单的与联结表的多对多关系:

如何首先使用实体​​框架数据库检索产品的相关类别?

我为此目的使用这个 sql 查询:

SQL 查询:

SELECT Products.*, Categories.Title
FROM Products, Products_Categories, Categories
WHERE (Products.ID = Products_Categories.Product_ID AND Products_Categories.Category_ID = Categories.ID)

什么是等效的 lambda 表达式


经过大量研究,我尝试了以下代码:

HomeController 中的 C#:

products = oDB.Products.Include(m => m.Products_Categories.Select(a => a.Category))
                       .ToList();

之后我应该使用以下方法之一来访问产品的类别标题:

// i and j are indices
string title = products[i].Products_Categories.Select(x => x.Category).ToList()[j].Title;
string title_0 = products[i].Products_Categories.ToList()[j].Category.Title;

这段代码的问题是当我将产品对象传递给这样的视图时,我无法访问类别:

return View(products);

我正在寻找一些这样的代码:

在 .cshtml 文件中:

@model List<olomrayanehDB.Product>
...
@item.Products_Categories.Category.Title // ERROR! this is not working for many to many relations, but I know there's almost the same way coding for one to many relations.

总之,我如何将 products 对象与所​​有相关数据(例如类别标题)一起传递给视图? (我知道一对多关系的解决方案,这里的问题是多对多关系与联结表

【问题讨论】:

    标签: asp.net-mvc entity-framework lambda


    【解决方案1】:

    不知道为什么你的对象没有被填充但是:

    您不需要在其中包含 Product_Categories。您可以让 EF 将其直接映射到 Products 中的 Category 列表。

    modelBuilder.Entity<Product>()
                .HasMany<Category>(s => s.Categories)
                .WithMany(c => c.Products)
                .Map(cs =>
                        {
                            cs.MapLeftKey("ProductId");
                            cs.MapRightKey("CategoryId");
                            cs.ToTable("Product_Category");
                        });
    

    【讨论】:

    • 对不起,我忘了说我先使用实体​​框架数据库。所以模型是自动创建的,连接表在.edmx中。
    猜你喜欢
    • 2011-07-22
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多