我有一個簡單的問題。我有 2 個模型、雞尾酒和配料:
public class Coctails
{
[Required]
public long CoctailsId { get; set; }
public string Name { get; set; }
public string CookingMethod { get; set; }
public double Price { get; set; }
public List<Ingredients> CoctailIngredients { get; set; }
}
public class Ingredients
{
[Required]
public long IngredientsId { get; set; }
public string Name { get; set; }
public double Amount { get; set; }
public double Price { get; set; }
public List<Coctails> CoctailsWithThisIngredient { get; set; }
}
我正在使用郵遞員根據以下要求保存 1 種成分:
{
"Name":"vodka",
"Amount":1000,
"Price":100}
之后,我嘗試通過發布請求添加新的雞尾酒:
{
"Name":"vodka s pivom" ,
"CookingMethod":"rubilovo",
"Price":100,
"coctailIngredients":
[
{
"Name" : "vodka",
"Amount" : 50
}
]}
我有無限回圈錯誤(但我需要這兩個欄位 CoctailIngredients 和 CoctailsWithThisIngredient 告訴 ef 這是多對多關系,它正在為我制作第三個連接表)......那么如何避免這種情況?
我的資料庫背景關系類:
public class DatabaseContext : DbContext
{
public DatabaseContext()
{
}
public DbSet<Coctails> Coctails { get; set; }
public DbSet<Ingredients> Ingredients { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Coctails>()
.HasMany(c => c.CoctailIngredients)
.WithMany(s => s.CoctailsWithThisIngredient)
.UsingEntity(j => j.ToTable("CoctailsWithIngredients"));
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Filename=BarDb.db");
}
}
我的POST方法:
[HttpPost]
public async Task<ActionResult<Coctails>> PostCoctails(Coctails coctails)
{
_context.Coctails.Attach(coctails);
await _context.SaveChangesAsync();
return CreatedAtAction("GetCoctails", new { id = coctails.CoctailsId }, coctails);
}
uj5u.com熱心網友回復:
保持多對多關系的唯一方法是添加第三個表。如果您使用 Ef core 5 ,ef 可以在 shadow 中為您創建此表,但最好顯式創建它:
public class CoctailIngridient
{
[Key]
public long Id { get; set; }
public long CoctailId { get; set; }
public long IngredientId { get; set; }
public virtual Coctail Coctail { get; set; }
public virtual Ingredient Ingridient { get; set; }
}
public class Coctail
{
[Key]
public long CoctailsId { get; set; }
public string Name { get; set; }
public string CookingMethod { get; set; }
public double Price { get; set; }
public List<CoctailIngredient> CoctailIngredients { get; set; }
//only for ef core 5
public List<Ingredient> Ingredients { get; set; }
}
public class Ingredient
{
[Key]
public long IngredientId { get; set; }
public string Name { get; set; }
public double Amount { get; set; }
public double Price { get; set; }
public List<CoctailIngredient> CoctailIngredients { get; set; }
//only for ef core 5
public List<Coctail> Coctails { get; set; }
}
uj5u.com熱心網友回復:
添加第三個模型類并從資料庫背景關系方法中洗掉 OnModelCreating 方法就行了。我想問題解決了。感謝幫助!
還有一件非常重要的事情,我還在我的上面添加了“NotMapped”標簽
public List<Coctails> CoctailsWithThisIngredient { get; set; }
和
public List<Ingredients> CoctailIngredients { get; set; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/313348.html
標籤:C# 实体框架 .net核心 asp.net-web-api 实体框架核心
下一篇:谷歌腳本--發送電子郵件提醒
