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

前端 未结 9 1588
情深已故
情深已故 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 06:39

    I had a similar situation but in my case even setting Identity to off didn't help.

    The problem was connected with Primary Key, which I've missed to add in my Entity Model.

    Here is the script which was generating the model:

     CREATE TABLE [im].[SomeGroup]
     (
        [Id] INT NOT NULL IDENTITY(1,1), -- this is mandatory for EF
        [OtherGroupId] INT NOT NULL,
        [Title] NVARCHAR(512) NOT NULL
     )
    

    The C# code for above is:

    Insert(new SomeGroup
    {
      // I'm not providing Id here, cause it will be auto-generated
      SomeGroupId = otherGroup.Id,
      Title = otherGroup.Title
    });
    

    Here is also some explanation of that.

    0 讨论(0)
  • 2020-12-05 06:40

    Have you tried explicitly specifying the StoreGeneratedPattern?

    modelBuilder.Entity<BOB>()
        .HasKey(p => p.Id)
            .Property(p => p.Id)
                .StoreGeneratedPattern = StoreGeneratedPattern.None;
    
    builder.Entity<BOB>().MapSingleType().ToTable("BOB");
    
    0 讨论(0)
  • 2020-12-05 06:41

    It happened to me when I had a primary key missing on the respected column (the identity column) in the db's schema. I exported data between SQL servers, using SSMS Export tool and creating a new database, but didn't realize that it's exporting only the data, without keys.

    0 讨论(0)
  • 2020-12-05 06:51

    You could also use

    modelBuilder.Entity<BOB>()
        .HasKey(p => p.Id)
        .Property(p => p.Id)
        .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
    
    builder.Entity<BOB>().MapSingleType().ToTable("BOB");
    
    0 讨论(0)
  • 2020-12-05 06:53

    If you are using database first approach then first delete the respective entity from the edmx diagram and then Update the model from database , this will surely resolve your issue

    0 讨论(0)
  • 2020-12-05 06:56

    In my case EntityFramework generated this code inside Context.cs class:

    modelBuilder.Entity<MODEL_OF_TABLE>(entity =>
    {
        entity.Property(e => e.Id).ValueGeneratedNever(); // <= this line must remove
        ...
    }
    

    after remove this line, problem solved.

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