Code first - Cannot insert the value NULL into column 'Id'

萝らか妹 提交于 2019-12-31 17:50:20

问题


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

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

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

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

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

The error stack trace:

[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

Solution

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


回答1:


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

To solve this try:

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

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

or decorate your key in the POCO with:

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



回答2:


I ran into the same problem, found your question, and then noticed this Entity Framework 4.1 code-first KeyAttribute as non-identity column question ( which has an attribute that solved my problem ).

If you define User as:

public class User
{
    [DataMember, Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long ID { get; set; }

    [DataMember]
    public string Email { get; set; }
}

The key here is putting the attributes:

  • Key
  • DatabaseGenerated

onto the ID column. Apparently the issue we are fighting is that Entity Framework by default expects to do inserts with keys being identities.




回答3:


I fixed this by setting StoreGeneratedPattern on the column properties to Computed.

Step by step below:

  1. Open your EDMX (double click in Visual Studio)
  2. Right click on the column that causes the problem, select properties.
  3. Change StoreGeneratedPattern to be Computed.

Hope that helps somebody.



来源:https://stackoverflow.com/questions/7858099/code-first-cannot-insert-the-value-null-into-column-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!