Home > Enterprise >  Auto-increment ID in create method in ASP.NET MVC
Auto-increment ID in create method in ASP.NET MVC

Time:09-06

I create a controller for Category table and have generated CRUD metods.

enter image description here

In the CREATE action method, how can I make the CategoryID input disappear, and after entering CategoryName, the CategoryID column will automatically increment when adding a new entry to the table.

CodePudding user response:

I changed CategoryID from nvarchar(450) to int and switch identity specifiation to YES, next I deleted input from view and CategoryID from POST parameter. Now when im trying to add record to table i got exception:

InvalidOperationException: Unable to track an entity of type 'Category' because primary key property 'CategoryId' is null.

So i found that i have to add .ValueGeneratedOnAdd(); to OnModelCreating.

modelBuilder.Entity<Category>(entity =>
        {
            entity.Property(e => e.CategoryId).HasColumnName("CategoryID").ValueGeneratedOnAdd(); ;
        });

I added it and now i have two more exceptions when I want to add a record:

enter image description here

What can i do next to add a record correctly?

CodePudding user response:

You can just remove the controls (textbox and label) from your create view.

Additionally, you can remove it from the list of parameters the POST method is expecting example

Change this:

public ActionResult Create([Bind(Include = "CategoryID,CategoryName")] Category category)

to:

public ActionResult Create([Bind(Include = "CategoryName")] Category category)
  • Related