实体框架代码首先 - 不能在对象'db'中插入重复键 [英] Entity Framework Code First - Cannot insert duplicate key in object 'db'

查看:297
本文介绍了实体框架代码首先 - 不能在对象'db'中插入重复键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用新的EF代码到我的一个项目,我有一个奇怪的错误,我的模式是:

  abstract class Member 
{
public virtual int MemberId;
...其他东西

}

类用户:会员
{
public virtual string Name;
...一些更多的道具没有新的键定义
}

class MyDbContext
{
public DbSet< User>用户{get; set;}
}

部署到SQL Server的结果是好的,我有一个会员表和一个用户表(TPC)。
现在在我的主要我有以下代码:

  static Main()
{
用户x,y;
using(MyDbContext ctx = new MyDbContext())
{


x = ctx.Users.Create();
y = ctx.Users.Create();
x.Name =SomeUser;
y.Name =SomeUser2;
ctx.SaveChanges();

}
}

保存更改我得到: / p>


未处理的异常:
System.Data.Entity.Infrastructure.DbUpdateException:
更新
条目查看
de tails的内部异常--->
System.Data.UpdateException:更新条目时发生错误

看到内部
---> System.Data.SqlClient .SqlException:违反PRIMARY
KEY约束
'PK_ 用户 _0CF04B1821B6055D'。不能
在对象
'dbo.Users'中插入重复键


默认情况下,MemberId是身份,所以我只是不看到这里发生了什么我试图用新的创建实例,并将它们附加到上下文,但错误是一样的,任何想法?
数据库是空的!



谢谢。



编辑:忘记告诉会员是

解决方案

我刚刚在TPC中测试了它和派生类型的表格(每个具体类型的表格)继承在EF 4.1 RC中没有将PK定义为身份。


I'm using the new EF code first to one project of mine, and i'm getting a weird error, my mode is:

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;}
}

The result of the deployment to SQL Server is just ok, i've a Members Table and a Users Table (TPC). Now in my main i've the following code:

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();

   }
}

On save changes i get:

"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'."

The MemberId by default is identity so i just not seeing what's going on here. i've tried to create the instances with new and Attach them to the context but the error was the same, any ideas? The database is empty!

Thanks.

EDIT: Forgot to told that Member is an abstract class sorry bout that.

解决方案

I just tested it and tables of derived types in TPC (table per concrete type) inheritance don't have PK defined as identity in EF 4.1 RC.

这篇关于实体框架代码首先 - 不能在对象'db'中插入重复键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆