实体框架无法将值NULL插入列标识规范设置为否 [英] Entity Framework Cannot insert the value NULL into column Identity Specification set to No

查看:134
本文介绍了实体框架无法将值NULL插入列标识规范设置为否的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先使用实体​​框架代码,最近创建了一个名为ImportantCases的新Repo模型/表。



我已经像其他所有设置一样配置和模型当我在代码中得到这一行:

  public int CreateImportantCase(ImportantCase newImportantCase)
{
_context.ImportantCases.Add(newImportantCase);

_context.SaveChanges(); //< --- here

return newImportantCase.ImportantId;
}

我收到此错误:


无法将值NULL插入列ImportantId,表
'MyDatabase.dbo.ImportantCases';列不允许为空。 INSERT
失败。该语句已被终止。


我的模型/配置如下所示:



模型

  public class ImportantCase 
{
public int ImportantId {得到;组; }
public int EvpId {get;组; }
public string Comment {get;组; }
public int CategoryId {get;设置;}
}

EF配置

  class ImportantCaseConfiguration:EntityTypeConfiguration< ImportantCase> 
{
public ImportantCaseConfiguration()
{
HasKey(x => x.ImportantId);
}
}

在调用create方法之前,我正在设置通过Post方式,使用视图模型和模型绑定,新的 ImportantCase

  if(imp!= null)//已经是一个记录,所以更新
{
imp.Comment = modifiedExceptionPersonViewModel.Comment;
imp.CategoryId = int.Parse(modifiedExceptionPersonViewModel.SelectedCategory);
_service.UpdateImportantCase(imp);
}
if(imp == null)// no record so create
{
ImportantCase newImportantCase = new ImportantCase();
newImportantCase.Comment = modifiedExceptionPersonViewModel.Comment;
newImportantCase.CategoryId = int.Parse(modifiedExceptionPersonViewModel.SelectedCategory);
newImportantCase.EvpId = modifiedExceptionPersonViewModel.EvpId;
_service.CreateImportantCase(newImportantCase);我已经检查过 newImportantCase $ / code $ c> c $ c> SaveChanges 之前的对象,它看起来像我预料的那样, ImportantId 设置为'0'通常EF一旦写入完成就会创建ID。



然而,我注意到的一件事是,当我查看该表的设计时,身份规范设置为 ,EF创建的所有其他表都设置为,我做了什么不同?



note



EvpId 是从视图返回的viewmodel的ID,I我们刚刚将该类别和属性注释到此视图模型中,以便在控制器中单独处理它们。



编辑



我刚刚意识到,当我最初运行 update-database时,我愚蠢地将 ImportantId 设置为字符串,但是后来添加了一个新的迁移来纠正这个问题,没有意识到EF没有追溯地整理身份规范,有没有办法?

解决方案

我做了以下工作来纠正这个问题:



1)删除t通过管理工作室他有问题的表格。



2。)确保模型被修改为具有实际的Id(您想要的事物身份规范设置为是)



3。)通过包管理器控制台创建一个新的迁移,如:

 code> add-migration将ImportantId设置为身份规范

4)如果nothings更改您将看到一个空的 Up() Down()方法



5。)修改这些与最初引入此表的迁移内容,但请确保您将此ID设置为int,这样:

  public partial class addedimportantcasetable:DbMigration 
{
public override void Up()
{
CreateTable(
dbo.ImportantCases ,
c => new
{
ImportantId = c.String(nullable:false,maxLength:128),
EvpId = c.Int(nullable:false),
Comment = c.String ),
CategoryId = c.Int(nullable:false),
})
.PrimaryKey(t => t.ImportantId);
}

public override void Down()
{
DropTable(dbo.ImportantCases);
}
}

被复制到新的迁移中,但略有更改为这个:

  public partial class SetImportantIdasIdentitySpecification:DbMigration 
{
public override void Up()
{
CreateTable(
dbo.ImportantCases,
c => new
{
ImportantId = c.Int(nullable:false,identity:true)
EvpId = c.Int(nullable:false),
注释= c.String(),
CategoryId = c.Int(nullable:false),
})
.PrimaryKey(t => t.ImportantId);
}

public override void Down()
{
DropTable(dbo.ImportantCases);
}
}


Im using Entity Framework code first and have recently created a new Repo model/table called ImportantCases.

I have set up the configuration and model just like every other however when i get to this line in my code:

public int CreateImportantCase(ImportantCase newImportantCase)
        {
            _context.ImportantCases.Add(newImportantCase);

            _context.SaveChanges(); // <--- here

            return newImportantCase.ImportantId;
        }

I am getting this error:

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

My model/configuration look like this:

Model

public class ImportantCase
{
    public int ImportantId { get; set; }
    public int EvpId { get; set; }
    public string Comment { get; set; }
    public int CategoryId { get; set;}
}

EF Configuration

class ImportantCaseConfiguration : EntityTypeConfiguration<ImportantCase>
    {
        public ImportantCaseConfiguration()
        {
            HasKey(x => x.ImportantId);
        }
    }

Prior to calling the create method I am setting up the new ImportantCase via the Post method from the view using a view model and model binding:

if (imp != null ) // already a record, so update
                {
                    imp.Comment = modifiedExceptionPersonViewModel.Comment;
                    imp.CategoryId = int.Parse(modifiedExceptionPersonViewModel.SelectedCategory);
                    _service.UpdateImportantCase(imp); 
                }
                if (imp == null) //no record so create
                {
                    ImportantCase newImportantCase = new ImportantCase();
                    newImportantCase.Comment = modifiedExceptionPersonViewModel.Comment;
                    newImportantCase.CategoryId = int.Parse(modifiedExceptionPersonViewModel.SelectedCategory);
                    newImportantCase.EvpId = modifiedExceptionPersonViewModel.EvpId;
                    _service.CreateImportantCase(newImportantCase);
                }

I've inspected the newImportantCase object just before the SaveChanges and it looks as I would expect, with the ImportantId set to '0', usually EF will just create the ID once the write has completed.

One thing I have noticed however is the Identity Specification is set to No when I view the Design of that table, all the other tables that EF has created are set to Yes, what have I done differently?

note

EvpId is the Id of the viewmodel which is being returned from the view, I've just rolled the category and comment properties into this viewmodel in order to deal with them separately in the controller.

edit

I have just realised that I stupidly set the ImportantId to a string when I ran initially update-database but then added a new migration to rectify this later on, not realising EF does not retrospectively sort out the identity specification, is there a way around this?

解决方案

I did the following to rectify this issue:

1.) Delete the problematic table through management studio.

2.) Make sure the model is amended to have the actual Id (the thing you want as the Identity Specification set to Yes for)

3.) Through the Package Manager Console create a new migration, something like:

add-migration "Set ImportantId as Identity Specification"

4.) If nothings changed you will see an empty Up() and Down() method

5.) Modify these with the contents of the migration that initially introduced this table but make sure you set the Id to an int this time, so this:

public partial class addedimportantcasetable : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.ImportantCases",
                c => new
                    {
                        ImportantId = c.String(nullable: false, maxLength: 128),
                        EvpId = c.Int(nullable: false),
                        Comment = c.String(),
                        CategoryId = c.Int(nullable: false),
                    })
                .PrimaryKey(t => t.ImportantId);                
        }

        public override void Down()
        {
            DropTable("dbo.ImportantCases");
        }
    }

Is copied into the new migration, but slightly altered to this:

public partial class SetImportantIdasIdentitySpecification : DbMigration
    {
        public override void Up()
        {
            CreateTable(
               "dbo.ImportantCases",
               c => new
               {
                   ImportantId = c.Int(nullable: false, identity: true),
                   EvpId = c.Int(nullable: false),
                   Comment = c.String(),
                   CategoryId = c.Int(nullable: false),
               })
               .PrimaryKey(t => t.ImportantId);
        }

        public override void Down()
        {
            DropTable("dbo.ImportantCases");
        }
    }

这篇关于实体框架无法将值NULL插入列标识规范设置为否的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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