【发布时间】:2011-12-13 01:45:13
【问题描述】:
这是我的代码,很简单……
var newUser = new User();
newUser.Id=id;
newUser.Email = email;
this.DataContext.Set<User>().Add(newUser);
this.DataContext.SaveChanges();
我得到的错误是this.DataContext.SaveChanges(); 的 sqlexception 声明:
无法将值 NULL 插入到表的“Id”列中 'xxxxx.dbo.Users';列不允许空值。插入失败。
我已经调试过,发现 newUser 中的 Id & Email 有值
this.DataContext.Set<User>().Add(newUser);
如果是这种情况,值如何变为空?
错误堆栈跟踪:
[DbUpdateException: An error occurred while updating the entries. See the inner exception for details.]
System.Data.Entity.Internal.InternalContext.SaveChanges() +204
System.Data.Entity.Internal.LazyInternalContext.SaveChanges() +23
System.Data.Entity.DbContext.SaveChanges() +20
我一直无法理解或解决这个问题......
非常感谢您对此提供的任何帮助...
问候 阿纳布
解决方案
好的,感谢 Ladislav 为我指明了正确的方向:
添加属性[DatabaseGenerated(DatabaseGeneratedOption.None)] 解决了这个问题。
【问题讨论】:
-
id的类型是什么?会不会是在数据库中生成密钥时出了问题?
-
type 在 sqlserver 中是 bigint,在 User 类中它很长。而且当我使用没有 codefirst 的普通实体框架时,它可以工作
-
你是如何映射用户的?默认情况下,EF 代码首先需要在数据库中生成 Id 值(通过身份设置)。
-
我的用户类有两个字段,其中 Id 具有 [key] 属性。在 db 中,我已将 Id 设为主键,但已声明 IsIdentity =no ,因此不会在 db 中生成该值。 @Ladislav:你说的可能是问题所在,我该如何解决?我不能让 isIdentity=yes
-
好的,感谢 Ladislav 为我指明了正确的方向:添加属性 [DatabaseGenerated(DatabaseGeneratedOption.None)] 解决了问题。
标签: entity-framework-4.1 ef-code-first