代码第一 - 无法将值NULL插入列'Id' [英] Code first - Cannot insert the value NULL into column 'Id'

查看:428
本文介绍了代码第一 - 无法将值NULL插入列'Id'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,非常简单...

This is my code, very simple...

 var newUser = new User();
        newUser.Id=id;
        newUser.Email = email;
       this.DataContext.Set<User>().Add(newUser);
        this.DataContext.SaveChanges();

我得到的错误是在 this.DataContext.SaveChanges() ; 表示:

The error I get is a sqlexception at this.DataContext.SaveChanges(); stating that:


无法将值NULL插入列Id,表
' xxxxx.dbo.Users';列不允许为空。 INSERT failed。

Cannot insert the value NULL into column 'Id', table 'xxxxx.dbo.Users'; column does not allow nulls. INSERT fails.

我已调试,发现Id&电子邮件在newUser
this.DataContext.Set< User>()。Add(newUser);

I have debugged and found that there is value in Id & Email in newUser at this.DataContext.Set<User>().Add(newUser);

如果是这种情况,值如何变为null?

If this is the case, how is the value becoming null?

错误堆栈跟踪:

[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

我无法理解或解决这个问题....

I have not been able to understand or solve this....

真诚感谢任何帮助...

Would sincerely appreciate any help in this...

Regards
Arnab

Regards Arnab

解决方案

好的,谢谢Ladislav指点我正确的方向:
添加属性 [DatabaseGenerated(DatabaseGeneratedOption.None)] 解决了问题。

Ok, thanks to Ladislav to point me in the right direction: Adding the attribute [DatabaseGenerated(DatabaseGeneratedOption.None)] solved the problem.

推荐答案

参考这篇文章似乎实体框架预计默认插入到标识列。

Referring to this post it seems that entity framework expects by default that you insert into identity column.

要解决这个问题:

modelBuilder.Entity<BOB>()
    .HasKey(p => p.Id)
    .Property(p => p.Id)
    .StoreGeneratedPattern = StoreGeneratedPattern.None;

builder.Entity<BOB>().MapSingleType().ToTable("BOB");

或在POCO中装饰您的密钥:

or decorate your key in the POCO with:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)] //Fixed typo
public Int64 PolicyID { get; set; }

这篇关于代码第一 - 无法将值NULL插入列'Id'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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