如何通过Entity Framework访问多对多table? asp.net
How to access many-to-many table via Entity Framework? asp.net
如何通过 EF 读取多对多 table?我不知道如何使用多对多 table。假设 Product_Category
它得到 ProductID
和 CategoryID
。
我怎样才能通过例如
using(Entities db = new Entities)
{
/* cant access these here.. */}
方法??但是,我可以访问 Product_Category
,但无法访问其 ProductID
或 CategoryID
。
我想列出所有产品,例如其中 Product_Category.CategoryID == Category.ID
.
我以前从未使用过多对多 table,所以我很欣赏一些简单的示例如何通过 asp.net.
中的 EF 访问它们
谢谢
您必须使用桥 table Product_Category
加入产品和类别 table 以检索所需的产品信息。
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();
}
导航属性是你的朋友。除非你在路口 table 中有其他属性,否则你不需要它。这就是为什么您的模型中没有 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);
如果你确实想要一个明确的联结 tables 看这个:https://lostechies.com/jimmybogard/2014/03/12/avoid-many-to-many-mappings-in-orms/
如何通过 EF 读取多对多 table?我不知道如何使用多对多 table。假设 Product_Category
它得到 ProductID
和 CategoryID
。
我怎样才能通过例如
using(Entities db = new Entities)
{
/* cant access these here.. */}
方法??但是,我可以访问 Product_Category
,但无法访问其 ProductID
或 CategoryID
。
我想列出所有产品,例如其中 Product_Category.CategoryID == Category.ID
.
我以前从未使用过多对多 table,所以我很欣赏一些简单的示例如何通过 asp.net.
中的 EF 访问它们谢谢
您必须使用桥 table Product_Category
加入产品和类别 table 以检索所需的产品信息。
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();
}
导航属性是你的朋友。除非你在路口 table 中有其他属性,否则你不需要它。这就是为什么您的模型中没有 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);
如果你确实想要一个明确的联结 tables 看这个:https://lostechies.com/jimmybogard/2014/03/12/avoid-many-to-many-mappings-in-orms/