简体   繁体   中英

Entity Framework Cannot insert the value NULL into column Identity Specification set to No

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");
        }
    }

In model ImportantCase change int to int?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM