Entity Framework CTP 4. “Cannot insert the value NULL into column” - Even though there is no NULL value

前端 未结 9 1589
情深已故
情深已故 2020-12-05 06:21

Im using EF CTP 4. I have a simple console app (for testing purposes) that is using EF to insert some data into a SQL database.

I have come to a problem where by upo

相关标签:
9条回答
  • 2020-12-05 07:01

    i have the same issue here and it's really an ugly solution.

     [Key]
    public Int64 PolicyID { get; set; }
    

    this is NOT an auto generated number

    then i hit the same error.

    EF Code First CTP5

    after apply this:

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

    then it will work.

    0 讨论(0)
  • 2020-12-05 07:01

    I know that this question is somehow dated and an accepted solution has been already found, however I thought it would be useful if I share my findings.

    I had this error today because I was using two different instances of the same DataContext. I was creating a new model with some properties - values for these properties were loaded from the database using one instance of the DataContext, then I was trying to push this newly created model into database calling first Add() and then SaveChanges() on a different instance of the DataContext. After I started using the same instance for both getting the values for the properties and actually adding and saving the new object - everything started working.

    0 讨论(0)
  • 2020-12-05 07:03

    I'm using EF 4.1, Model First and came across this problem. Here's how I solved it:

    When using the Model Designer surface, when you create an Entity, you have to define a Key property, it defaults to Id, int32.

    In my situation, I've chosen to use Guids for the Id, so I'd switch the int32 to Guid. But if you examine this Id after you create the entity, I saw that the Id's 'StoreGeneratedPattern' had 'identity' selected. At first I didn't think that was a problem, but when I examined the SQL being used to insert into the database, it was a bit weird in that it wasn't sending my Id. Frustrating!

    But once I went back and changed the 'StoreGeneratedPattern' from 'identity' to 'none', regenerated the db and rebuilt the project, this strange message stopped happening:

    Cannot insert the value NULL into column 'Id', table 'TestDB.dbo.BOB'; column does not allow nulls. INSERT fails. The statement has been terminated.

    FYI - upon viewing the sql some more it seems that if you have identity chosen for StoreGeneratedPattern, the EF saves the object to the db (sans Id), then immediately fetches back the identity and saves that back to your object. i.e. this choice for StoreGeneratedPattern relies on the db to generate your Id, NOT your code!

    0 讨论(0)
提交回复
热议问题