首先使用代码创建了多到多个关系,首先使用类似的类来:
class Product
{
public int Id { get; set; }
public ICollection<Categorization> Categorizations { get; set; }
}
class Categorization
{
public int ProductId { get; set; }
public Product Product { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
class Category
{
public int Id { get; set; }
public ICollection<Categorization> Categorizations { get; set; }
}对于dbContext中的复合键,请执行以下操作
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Categorization>().HasKey(x => new { x.ProductId , x.CategoryId });
}我试图返回包含所有类别的产品的JSON,反之亦然。使用这种方法:
var prod = _context.Products
.Include(p => p.Categorization)
.FirstOrDefault(p => p.Id == 1));我得到了
{
"product": {
"id": 1,
"categorizations": [
{
"categoryId": 1
}
]
}
}这也切断了后面的任何东西,例如另一个领域。
使用这种方法:
var prod= _context.Products
.Select(p => new
{
p.Id,
p.Categorization
})
.FirstOrDefault(p => p.Id == 1);我得到了
{
"product": {
"id": 1,
"categorizations": [
{
"categoryId": 1,
"category": null,
"productId": 1,
"product": null
},
{
"categoryId": 2,
"category": null,
"productId": 1,
"product": null
},
]
}
}我如何才能:
发布于 2016-08-05 20:23:11
我建议您从文档中阅读加载相关数据部分。
以下是你的一些具体问题的答案:
(1)使用include获取引用对象“类别”的属性。
你应该使用ThenInclude
var prod = _context.Products
.Include(p => p.Categorization)
.ThenInclude(c => c.Category)
.FirstOrDefault(p => p.Id == 1));(2)使用select获取引用对象“类别”的属性。
您可以使用嵌套投影(选择):
var prod = db.Products
.Where(p => p.Id == 1)
.Select(p => new
{
p.Id,
Categories = p.Categorizations.Select(c => c.Category).ToList()
})
.FirstOrDefault();那么问题(3)呢,你需要提供一个具体的例子才能得到一个具体的答案。
https://stackoverflow.com/questions/38795933
复制相似问题