1

I have context with Animal entity and Id as Identity column.

This is Animal definition:

public class Animal
{
    [Key, Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
}

There is only one animal in collection:

Animals: [{
    Id: 1,
    Name: "Dog"
  }].

I want to insert new Animal with following code:

context.Animals.Add(new Animal { Name: "Cat" })

Following exception is thrown:

System.InvalidOperationException: 'The instance of entity type 'Animal' cannot be tracked because another instance of this type with the same key is already being tracked.

6
  • What line generates the exception - Add or SaveChanges? Commented Apr 5, 2018 at 7:34
  • 1
    Seems that EF already tracked Animal entity. You need to use already tracked entity to add new data (also provide part of code which throwing exception). Commented Apr 5, 2018 at 7:34
  • I guess you are trying to insert same key i.e Id:1 Commented Apr 5, 2018 at 7:49
  • @IvanStoev Add is generating exception Commented Apr 5, 2018 at 7:49
  • 1
    Apparently there is something not shown in the question. minimal reproducible example needed. Commented Apr 5, 2018 at 7:54

1 Answer 1

2

Which database do you use? If it is InMemoryDatabase from Microsoft.EntityFrameworkCore.InMemory and first animal was added with explicit id (by context.Animals.Add(new Animal { Id: 1, Name: "Cat" })) then InMemoryDatabase does not increment internal identity counter used for id setting. So when you and second animal, InMemoryDatabase try to set Id to 1 but there is already animal with this id, so exception was thrown.

You have two solution:

  • Removed explicit id from first animal (I prefer this)
  • Explicity set id in second (and all next animals)
Sign up to request clarification or add additional context in comments.

3 Comments

That is exactly what is happening
So I add two possible solutions
Third option (strongly recommended): don't use InMemoryDatabase but test against an actual database (integration test). You shouldn't change code with the sole purpose to satisfy unit tests.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.