我首先在我的一个项目中使用新的 EF 代码,我遇到了一个奇怪的错误,我的模式是:
abstract class Member
{
public virtual int MemberId;
... some other stuff
}
class User : Member
{
public virtual string Name;
... some more props no new key defined
}
class MyDbContext
{
public DbSet<User> Users {get;set;}
}
部署到 SQL Server 的结果很好,我有一个成员表和一个用户表 (TPC)。 现在在我的主要我有以下代码:
static Main()
{
User x,y;
using(MyDbContext ctx = new MyDbContext())
{
x = ctx.Users.Create();
y = ctx.Users.Create();
x.Name = "SomeUser";
y.Name = "SomeUser2";
ctx.SaveChanges();
}
}
保存更改时我得到:
"Unhandled Exception: System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for de tails. ---> System.Data.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient .SqlException: Violation of PRIMARY KEY constraint 'PK_Users_0CF04B1821B6055D'. Cannot insert duplicate key in object 'dbo.Users'."
默认情况下,MemberId 是身份,所以我只是看不到这里发生了什么。我试图用 new 创建实例并将它们附加到上下文,但错误是一样的,有什么想法吗? 数据库为空!
谢谢。
编辑:忘记告诉 Member 是一个抽象类,抱歉。
最佳答案
我刚刚测试了它,TPC 中的派生类型表 (每个具体类型的表) 继承在 EF 4.1 RC 中没有将 PK 定义为标识。
关于c# - Entity Framework 代码优先 - 无法在对象 'db' 中插入重复键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5449724/