简体   繁体   English

实体框架 CTP 4.“无法将 NULL 值插入列” - 即使没有 NULL 值

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

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.我使用 EF CTP 4。我有一个简单的控制台应用程序(用于测试目的),它使用 EF 将一些数据插入到 SQL 数据库中。

I have come to a problem where by upon inserting the item我遇到了一个问题,在插入项目时

using(var context = GetContext())
{
   BOB b = new BOB();
   b.Id = 1;

   context.Bobs.Add(b);
   context.SaveChanges();
}

It throws the error: {"Cannot insert the value NULL into column 'Id', table 'TestDB.dbo.BOB'; column does not allow nulls. INSERT fails.\\r\\nThe statement has been terminated."}它抛出错误: {“无法将值 NULL 插入列 'Id',表 'TestDB.dbo.BOB';列不允许为空。INSERT 失败。\\r\\n语句已终止。”}

The Table just has 1 field of Id int NOT NULL which is the primary key and is not an auto incremented Id.该表只有 1 个Id int NOT NULL字段,它是主键,不是自动递增的 Id。

On the creation of the DataContext I have this configuration, which yes does get fired.在创建 DataContext 时,我有这个配置,是的确实会被解雇。

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<BOB>().HasKey(b => b.Id);
    builder.Entity<BOB>().MapSingleType().ToTable("BOB");
}

I have also pre-populated this table and then through the debugger been able to via watch load up this BOB object... so I am really stumped, as for being able to load up my BOB shows that all is right... however upon inserting a new one it crashes...我也预先填充了这个表,然后通过调试器能够通过watch加载这个 BOB 对象......所以我真的很难过,至于能够加载我的 BOB 表明一切正常......但是插入一个新的它会崩溃......

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 EF Code First CTP5

after apply this:应用此后:

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

then it will work.那么它会起作用。

I'm using EF 4.1, Model First and came across this problem.我正在使用EF 4.1, Model First并遇到了这个问题。 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 .当使用模型设计器表面时,当你创建一个实体时,你必须定义一个Key属性,它默认为Id, int32

In my situation, I've chosen to use Guids for the Id , so I'd switch the int32 to Guid .在我的情况下,我选择使用Guids作为Id ,所以我将int32切换到Guid But if you examine this Id after you create the entity, I saw that the Id's 'StoreGeneratedPattern' had 'identity' selected.但是,如果您在创建实体后检查此 Id,我会看到 Id 的'StoreGeneratedPattern' 'identity'选择了'identity' 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.起初我不认为这是一个问题,但是当我检查用于插入数据库的 SQL 时,有点奇怪,因为它没有发送我的 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:但是,一旦我回去将'StoreGeneratedPattern''identity'更改为'none' ,重新生成数据库并重建项目,这个奇怪的消息就停止发生了:

Cannot insert the value NULL into column 'Id', table 'TestDB.dbo.BOB';无法将值 NULL 插入列“Id”、表“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.仅供参考-通过查看SQL的更多一些,似乎如果你有identity选择了StoreGeneratedPattern的EF保存对象,以分贝(没有编号),然后马上回来取的身份,并保存该回你的对象。 ie this choice for StoreGeneratedPattern relies on the db to generate your Id, NOT your code!StoreGeneratedPattern这个选择依赖于数据库来生成您的 ID,而不是您的代码!

Have you tried explicitly specifying the StoreGeneratedPattern ?您是否尝试过明确指定StoreGeneratedPattern

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

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

You could also use你也可以使用

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

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

It happened to me when I had a primary key missing on the respected column (the identity column) in the db's schema.当我在 db 模式中的受尊重列(身份列)上缺少主键时,这发生在我身上。 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.我在 SQL 服务器之间导出数据,使用 SSMS 导出工具并创建一个新数据库,但没有意识到它只导出数据,没有密钥。

I had a similar situation but in my case even setting Identity to off didn't help.我有类似的情况,但在我的情况下,即使将Identity设置为off也无济于事。

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:上面的 C# 代码是:

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.这里也有一些解释。

如果您使用的是数据库优先方法,那么首先从 edmx 图中删除相应的实体,然后从数据库中更新模型,这肯定会解决您的问题

In my case EntityFramework generated this code inside Context.cs class:就我而言,EntityFramework 在Context.cs类中生成了此代码:

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

after remove this line, problem solved.删除此行后,问题解决。

Ran into this issue as well.也遇到了这个问题。 For me my Dev DB Table for some reason didn't bring over the Key so EF didn't define my ID as a key.对我来说,我的开发数据库表由于某种原因没有带来密钥,所以 EF 没有将我的 ID 定义为密钥。

Note to anyone with this issue: Make sure that your table that you trying to insert a new record into with an ID field is actually defined in your Context class.遇到此问题的任何人请注意:确保您尝试将新记录插入到带有 ID 字段的表实际上是在您的 Context 类中定义的。

modelBuilder.Entity<CustomerEmail>(entity =>
        {
            entity.HasKey(e => e.Id)
                .HasName("PK_tblCustomerEmail");

            entity.Property(e => e.Customer).IsUnicode(false);

            entity.Property(e => e.Email).IsUnicode(false);
        });

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 .我今天遇到了这个错误,因为我使用了同一个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 .我正在创建一个具有一些属性的新模型 - 这些属性的值是使用DataContext一个实例从数据库加载的,然后我试图将这个新创建的模型推送到数据库中,首先调用Add()然后调用SaveChanges() 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.在我开始使用相同的实例来获取属性值并实际添加和保存新对象之后 - 一切都开始工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架 - 无法将值 NULL 插入列中? - Entity Framework - Cannot insert the value NULL into column? 无法将值 NULL 插入列 C# 实体框架 - Cannot insert the value NULL into column C# Entity Framework 无法将值 NULL 插入到列“Id”中,实体框架 - Cannot insert the value NULL into column 'Id', Entity framework 实体框架非标识 - 无法将值NULL插入列“ID” - Entity Framework Non Identity - Cannot insert the value NULL into column 'ID' 实体框架无法将值 NULL 插入设置为否的列标识规范 - Entity Framework Cannot insert the value NULL into column Identity Specification set to No 即使使用MVC4和Entity Framework指定了值,TryUpdateModel也会在插入时将属性设置为null - TryUpdateModel sets property to null on insert even though a value is specified, using MVC4 and Entity Framework 即使使用值实体框架,实体属性也为null - Entity property is null even with value entity framework “无法将值NULL插入列”,但我的列为Nullable…Entity Framework 5 asp.net MVC - “Cannot insert the value NULL into column ” but my column is Nullable… Entity Framework 5 asp.net MVC 无法将值 NULL 插入到 ASP.NET MVC 实体框架中的列中 - Cannot insert the value NULL into column in ASP.NET MVC Entity Framework 无法将值NULL插入列中 - Cannot insert the value NULL into column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM