Issues with TPC inheritance with entity infrastructure

I have 2 objects that I want to save separately in two different tables. Let the class calls Foo and FooTemp.

I use Table Per Concrete Type (TPC) type inheritance, because I want the FooTemp class to extend the Foo class, and I want the data to be stored separately.

The only difference between the two tables is that FooTemp has an extra field.

I followed this tutorial on setting up TPC inheritance . The only difference is that I have an extra field in my derived class.

Now here is my problem. When I add a new record to the database, I get an error:

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

Why am I getting this error? Is there any other way to do inheritance and store data in separate tables?

+3
source share
1 answer

I believe there is a problem with TPC if you define auto-generated authentication keys in both tables. Although this is not a problem from the point of view of SQL Server (because the two tables are separate and therefore can have records with the same key), the Entity Framework does not allow two objects that have the same base class to have the same key value. But this can happen if you have auto-generated keys on both tables with the same seed (e.g. 1).

, . , , , , Foo FooTemp, .

, , :

// Imagine, you know that there is a Foo with Key 1 already in the DB, or you
// could also query for that Foo to attach to the context
Foo foo = new Foo() { Key = 1 }; 
context.Foos.Attach(foo);
// Now, we have an object of type Foo with Key 1 in the object context

// Let assume, that the table FooTemp in the DB is empty. We create the
// first FooTemp
FooTemp fooTemp = new FooTemp();
context.Foos.Add(fooTemp);

context.SaveChanges();
// If the FooTemp table has an autogenerated identity with seed 1 in the DB,
// our FooTemp gets Key 1 in the DB. Because Entity Framework accepts the
// DB changes after calling SaveChanges, our FooTemp object will now have
// the Key 1, so we have a second Foo (since FooTemp derives from Foo) with
// the same Key 1 in the same object context

, :

  • , , , - .
  • .
+2

All Articles