我需要将两个对象分别存储在两个不同的表中。让我们调用类Foo和FooTemp。
我使用每种具体类型的表继承(TPC)继承,因为我希望类FooTemp扩展类Foo,并且希望将数据单独存储。
两个表之间唯一的区别是FooTemp有一个额外的字段。
我跟踪了本指南用于设置TPC继承。唯一的区别是我在派生类中有一个额外的字段。
现在,我的问题是。当我向数据库添加一个新记录时,我会得到以下错误:
"System.ArgumentException:已添加了具有相同密钥的项“
为什么我会有这个错误?还有其他方法来进行继承和将数据存储在单独的表中吗?
发布于 2011-03-11 15:02:40
如果要在两个表中定义自动生成的标识键,我相信TPC会出现问题。尽管从Server的角度来看,这不是一个问题(因为两个表是分开的,因此可以具有相同的键记录) Entity不允许共享相同基类的两个对象具有相同的键值。但是,如果在两个表上都有具有相同标识种子(例如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's 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我看到的解决办法是:
https://stackoverflow.com/questions/5273106
复制相似问题