Why is EF Core 2.0 seemingly generating the wrong value?

auto-generate c# entity-framework-core

Question

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.

1
1
7/31/2018 8:26:48 PM

Accepted Answer

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

0
7/31/2018 8:24:55 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow