Entity Framework - an object with a composite primary key
I'm using Entity Framework 4 and I've recently changed one of the objects' primary key to contain 2 columns instead of 1 (it used to have only its id - Guid - and now it has an id and a version - int).
When I'm trying to create another object with the same id but a different version, I get the following exception:
The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges.
I looked in the database and I do have 2 objects with the same id but with different versions, like I intended.
How can I make EF cooperate with those settings?
The enti开发者_运维百科ty's setting from the edmx file:
<EntityType Name="Test">
<Key>
<PropertyRef Name="TestID" />
<PropertyRef Name="TestVersion" />
</Key>
<Property Type="Guid" Name="TestID" Nullable="false" />
<Property Type="Int32" Name="FolderID" Nullable="false" />
<Property Type="String" Name="Name" Nullable="false" MaxLength="Max" FixedLength="false" Unicode="false" />
<Property Type="Int32" Name="TestVersion" Nullable="false" />
<Property Type="DateTime" Name="Date" Nullable="false" />
<Property Type="String" Name="Owner" Nullable="false" MaxLength="Max" FixedLength="false" Unicode="false" />
<Property Type="Binary" Name="TestObject" Nullable="false" MaxLength="Max" FixedLength="false" />
<NavigationProperty Name="Folder" Relationship="Labster7Model.FK_Tests_Folders" FromRole="Test" ToRole="Folder" />
<Property Type="String" Name="Description" Nullable="false" MaxLength="Max" FixedLength="false" Unicode="false" />
</EntityType>
I'll supply any other needed code parts.
Edit:
The table definition:The guid is set in the application.
Edit 2:
I have 2 such objects in my DB for testing. I just saw that when looking at the context's Tests collection, it has one of them duplicated twice instead of having 2 different objects (with different versions and dates).Delete all tables inside the EMDX and them re add them after updating you database this will do the drill
精彩评论