lar*_*z11 7 c# entity-framework-core
我目前正在使用 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; }
}
Run Code Online (Sandbox Code Playgroud)
但是,我不确定如何实现这一目标。昨天我遇到了另一个 SO 问题,它提出了这样的建议:
public IActionResult Meals () {
var meal = this.context.Meals
.Include(m => m.Pictures.Select(p => p.Id))
.First();
return new JsonResult(meal);
}
Run Code Online (Sandbox Code Playgroud)
然而,这会引发 InvalidOperationException。我的 DbContext 是非常基本的,没有 onModelConfiguring,因为据我所知,这段代码遵循约定,它只有两个相应类型的 DbSet。外键在数据库中也是正确的,并且调用如下:
var pictures = dbContext.Pictures.Where(p => p.MealId == mealId).ToList();
Run Code Online (Sandbox Code Playgroud)
按预期工作。我只包含了我认为相关的代码。如果需要更多,我会包括它,但我认为这完全是我对查询的有限理解。
感谢您的时间!
您不需要更改数据库结构,一种选择如下:
var db = this.context;
var result = (from meal in db.Meals
where meal.<whatever> == "123"
select new
{
Id = meal.Id,
Title = meal.Title,
Description = meal.Description,
//other required meal properties here.
PictureIds = meal.Pictures.Select(x => x.Id)
}).ToList();
Run Code Online (Sandbox Code Playgroud)
您也可以通过 lambda 以及使用“Select”方法执行相同的操作,Linq 在此类事情中对我来说似乎更直观,但是,对每个人来说......这是您的选择。