![](/img/trans.png)
[英]Entity framework core The instance of entity type cannot be tracked because another instance with the same key value
[英]Entity Framework Core : instance of entity type cannot be tracked because another instance with same key value
我正在共享一個我試圖保存更改但收到錯誤實體類型實例無法跟蹤的內容。
static async Task NoTracking(CookbookContextFactory factory)
{
using var dbcontext = factory.CreateDbContext();
//select query
var newDishIngredient = new DishIngridient { MyID = 103, Amount = 10, Description = "Sample" };
var newDishIngridientCopy = new DishIngridient { MyID = 103, Amount = 10, Description = "Sample" };
dbcontext.Ingridients.Add(newDishIngredient);
dbcontext.Ingridients.Add(newDishIngridientCopy);
await dbcontext.SaveChangesAsync();
var dish = new Dish
{
Title = "Foo",
Ingridients = new List<DishIngridient> { newDishIngridientCopy }
};
dbcontext.Dishes.Add(dish);
await dbcontext.SaveChangesAsync();
}
我知道我正在創建以復制相同的 id,但是由於某些業務邏輯,它在 EF Core 3 之前工作正常,現在它已經因上述錯誤而崩潰,因此我需要有這樣的行為。
我將按照您的示例代碼進行操作。
static async Task NoTracking(CookbookContextFactory factory)
{
using var dbcontext = factory.CreateDbContext();
//select query
var newDishIngredient = new DishIngridient { MyID = 103, Amount = 10, Description = "Sample" };
var newDishIngridientCopy = new DishIngridient { MyID = 103, Amount = 10, Description = "Sample" };
dbcontext.Ingridients.Add(newDishIngredient);
await dbcontext.SaveChangesAsync();
var dish = new Dish
{
Title = "Foo",
Ingridients = new List<DishIngridient> { newDishIngridient }
};
dbcontext.Dishes.Add(dish);
await dbcontext.SaveChangesAsync();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.