huysentruitw / entity-framework-core-mock

Easy Mock wrapper for mocking EFCore5 DbContext and DbSet using Moq or NSubstitute
MIT License
132 stars 24 forks source link

System.ArgumentException : An item with the same key has already been added. Key: (1) #53

Closed dzeidman closed 1 year ago

dzeidman commented 1 year ago

I am setting up a DBContext and adding some initial values. My context structure contains a master/slave relationship. The ids of the existing data are already added as unique values (the ids are ints decorated with [Key [DatabaseGenerated(DatabaseGeneratedOption.Identity)]). When I then add a new master record with a slave child, I get the error as above.

Not sure how to resolve this. It seems as though the mock does not generate new ids but it is supposed to according to the documentation.

dzeidman commented 1 year ago

I think that I worked it out. Or at least I have a workaround.

In my initial data I was assuming that this was data that existed in the database. I was therefore adding ids to each object as I expected to see them.

However, when I removed all the ids, the mock added ids to them so that when I then ran my test everything worked as expected.