简体   繁体   中英

Entity Framework Core : instance of entity type cannot be tracked because another instance with same key value

I am sharing a in which I am trying to save changes but getting error Instance of entity type cannot be tracked.

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();
}

I know I am creating to copy on same id, but I need to have such behaviour due to some business logic it was working fine till EF Core 3 now it has crashed with the above error.

I am going by your example code.

  1. I am assuming that MyId is the primary for DishIngridient entity.
  • Now here If I look you have two entity with MyId. This is wrong. When entity added to dbcontext it is always tracked. You have that provision when you read from that you want to track or not. Without tracking you can not save as there is no change.
  1. Why you need copy to add it into dish? You can directly add first entity.
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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM