[英]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.