[英]Save Related Data (Many to Many) in EF Core 5 without getting the actual records
我正在为午餐预订创建一个网络应用程序。
public class Food : BaseEntity
{
public int FoodId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Ingredients { get; set; }
public string PhotoPath { get; set; }
public ICollection<Menu> Menus { get; set; }
/*public ICollection<LunchReservation> LunchReservations { get; set; } omit */
}
public class Menu : BaseEntity
{
public Menu()
{
DateCreated = DateTimeOffset.Now;
DateModified = DateTimeOffset.Now;
}
public int MenuId { get; set; }
[Column(TypeName = "date")]
public DateTime MenuDate { get; set; }
public bool IsPublished { get; set; }
public ICollection<Food> Foods { get; set; }
/*public ICollection<LunchReservation> LunchReservations { get; set; } omit */
}
一切正常,但是当我想创建一个可以包含 1 种或更多食物的菜单时,出现错误。
这是我用于创建菜单的 Dto
public class MenuCreationDto
{
public int[] FoodIds { get; set; }
public string MenuDate { get; set; }
}
并且此代码不适用于保存。
var foods = menuCDto.FoodIds.Select(f => new Food() { FoodId = f }).ToList();
Menu newMenu = new()
{
MenuDate = menuDateInGregorian,
Foods = foods
};
await _db.Menus.AddAsync(newMenu);
await _db.SaveChangesAsync();
但是为了保存食物,此代码有效,但我不想从数据库中获取食物来制作菜单。
var foods = _db.Foods.Where(f => menuCDto.FoodIds.Contains(f.FoodId)).ToList();
Menu newMenu = new()
{
MenuDate = menuDateInGregorian,
Foods = foods
};
await _db.Menus.AddAsync(newMenu);
await _db.SaveChangesAsync();
在不从数据库中获取实际食物的情况下,如何将菜单保存到数据库中?
您可以在非工作示例中使用假(又名存根)实体
var foods = menuCDto.FoodIds.Select(f => new Food() { FoodId = f }).ToList();
但是在让 EF Core 添加父实体 ( Menu
) 之前,您必须让它知道这些是“现有”实体,否则它会将它们视为“新”实体并尝试插入新的Food
记录,而不是按预期方式插入链接. 您可以通过将它们附加到上下文来做到这一点,上下文将它们标记为存在且未更改:
_db.AttachRange(foods);
其余的代码将是相同的,但现在应该可以工作了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.