WCF RIA Services – An entity with the same identity already exists in this EntitySet.
WCF RIA Services is pretty powerful and does a lot for you when it comes to quickly building business applications. I came across something interesting today when I was working with a client.
For this post, I am going to be focusing on WCF RIA Services in conjunction with the EntityFramework. It turns out that if you have designed your tables with identities and you have set your seed for the table to be zero (0), then you will have problems right after your first record has been created and saved to the database.
The following is a screen shot of a given table in SQL Server with the identity seed set at zero (0):
The moment you try to create a subsequent record, you will get the following error:
InValidOperationException was unhandled by user code: An entity with the same identity already exists in this EntitySet.
The reason for this is that RIA Services tries to created a new record that has an identity of zero (0) and as soon as you try and add it to the underlying collection it throws an exception since a record with that value already exists.
In WCF RIA Services, I don’t believe there is a way to change the default behavior for when a new record is inserted. It looks like it follows whatever datatype is defined as the identity column that in the table. So if the column is defined as an integer than the default value would be zero (0).
I believe I remember being able to bypass this issue in ADO.NET with DataSets with the ability to define what the default value would be for adding a new record.
More than anything else, I wanted you to be aware of a possible exception that may not intuitively makes sense at first but then becomes clear once you see the data. You may get tricked into thinking that your system is working if you have an empty table and insert your first record. This will work perfectly fine since it will insert a record with the identity value being zero (0). The moment you try to add an additional record you will get the exception mentioned above.
I would like to stress that for most scenarios you should not need be concerned unless your team has designed your tables with the seed of your identity columns to be zero (0) instead of one (1). In SQL Server 200X, the default value for the seed of an integer identity is one (1).
Hope this helps to prevent any confusion. Also, if anyone knows how to rememdy this problem please let me know.