【发布时间】:2016-08-04 07:21:49
【问题描述】:
我目前正在开发一个带有 ASP.NET Core 和实体框架核心的 API,并使用 npgsql 作为数据库提供程序。我有两个实体,它们有一对多的关系。问题是我只想在“父控制器”返回的 JSON 结果中包含子实体的 ID。
这些是我的实体:
public class Meal {
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string UserId { get; set; }
public User User { get; set; }
public List<Picture> Pictures { get; set; }
public Meal () {
this.Pictures = new List<Pictures>();
}
}
public class Picture {
public int Id { get; set; }
public int MealId { get; set; }
public Meal Meal { get; set; }
public byte[] full { get; set; }
public byte[] small { get; set; }
}
但我不确定如何实现这一目标。昨天我遇到了另一个 SO 问题,它提出了这样的建议:
public IActionResult Meals () {
var meal = this.context.Meals
.Include(m => m.Pictures.Select(p => p.Id))
.First();
return new JsonResult(meal);
}
然而,这会引发 InvalidOperationException。 我的 DbContext 非常基本,没有 onModelConfiguring 因为据我所知此代码遵循约定,并且它只有两个相应类型的 DbSet。外键在数据库中也是正确的,并且调用如下:
var pictures = dbContext.Pictures.Where(p => p.MealId == mealId).ToList();
按预期工作。我只包含了我认为相关的代码。如果需要更多,我会包含它,但我认为这完全是我对查询的有限理解。
感谢您的宝贵时间!
【问题讨论】: