Search code examples
c#entity-framework-coreauto-generate

Why is EF Core 2.0 seemingly generating the wrong value?


I'm using the InMemoryDatabase for my unit tests. In my unit test I add some data to my derived DbContext via _context.Add(new Item(){Description="desciption"}).

In my test, I'm adding a new entity. I get a key conflict.

My repository method

//Before this method runs _context.Item already has one Item with Id = 1 which I set up in my unit test.
public async Task CreateItem(ItemDM dm){
    Item newItem = new Item(){Name = dm.RelatedItem.Process.Name}; //Id is zero here
    _context.Add(newItem); // The Error happens here
    _context.SaveChanges();
}

The error I'm getting is "same key value for {"id"} is already being tacked. When attaching existing entities, ensure that only one entity instance with a given key value is attached."

It was my understanding that EF Core would increment the Id appropriately but that seems to not be the case.


Solution

  • The reason this was happening is because I was adding my entities with a hardcoded value. E.g. .Add(new Item(){Id = 1}) My assumption is that the auto-generating capability would recognize this and update accordingly. I was wrong.

    Props to @Ivan Stoev for the information provided in the comments