【发布时间】: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