开发者

Table-per-type inheritance insert problem

I followed this article on making a table-per-type inheritance model for my entities, but I get the following error when I try to add an instance of a subclass to the database.

Here is how I create the subtype:

var cust = db.Users.CreateObject<Customer>(); // Customer inherits User
db.Users.AddObject(cust);
db.SaveChanges();

I get the following error when I make that last call:

"A value shared across entities or associations is generated in more than one location. Check that mapping does not split an EntityKey to multiple store-generated columns."

With the following inner exception:

"An item with the same key has already been added."

Any ideas on what I could be missing?

UPDATED WITH REPRO STEPS

Created a blank MS SQL Server 2008 R2 database, and added the following two tables:

Users

  • Id : bigint (PK and set it as the identity column)
  • Name : nvarchar(25) NOT NULL (whatever, some random property

Customers

  • Id : bigint (PK, identity column, and FK on Users.Id)
  • Title : nvarchar(25) NOT NULL (also whatever, some random property)

Next I generated the .edmx entity model from the database, and followed the link at the top verbatim. That is to say, I deleted the association between User and Customer, set User as the base class of Customer, deleted the Id property from the Customer entity, and made sure that the Customer.Id column was mapped to the inherited User.Id property. I then ran the following small program:

using (var db = new EF_Test.testEntities())
{
    var cust = db.Users.CreateObject<Customer>();
    db.Users.AddObject(cust);
    db.Sav开发者_StackOverflow社区eChanges();
}

I get the same exceptions I described above. Please let me know if this repro works for you, and if it does, what I'm doing wrong. I'm blocked on this issue.


I finally found the source of my troubles. For those still interested, in the Customers table, the Id column should not have been set to the identity column of the table (PK and the FK dependency are fine though).


ObjectContext.CreateObject() both creates an instance of T and simultaneously adds that instance to the ObjectContext instance from which CreateObject() was called. So, your explicit call to AddObject() fails because a Customer object with the same key already exists. The correct code is:

var cust = db.Users.CreateOjbect<Customer>();
// modify any properties on the customer instance
db.SaveChanges();


In my case the problem was that the legacy part of our code used Map in EntityTypeConfiguration and I added a property to Item which caused the EF to split the Item entity in two tables: dbo.Item and dbo.Item1. Solution was to look in the db on the properties in Item1 table and adding them to the explicit mapping.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜