sunny
sunny

Reputation: 69

MVC5 Primary key always takes sequence

I have a mvc5 application in which I am trying to create new rows in my model. But the primary key for the table is always in a sequence.

But I want the key I give in view to be used as primary key. I am new to MVC and I am not sure what I am doing wrong here.

This is my controller

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ProviderId,ProviderName")] Provider provider)
    {
        if (ModelState.IsValid)
        {
            db.Providers.Add(provider);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(provider);
    }

I can see that while debugging that value in provider is what I input from the view.

Here is my part of my view:

<div class="form-group">

    @Html.LabelFor(model => model.ProviderId, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.ProviderId, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.ProviderId, "", new { @class = "text-danger" })
    </div>

        @Html.LabelFor(model => model.ProviderName, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.ProviderName, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.ProviderName, "", new { @class = "text-danger" })
    </div>

</div>

here is my model class :

public class Provider
{
    [Key]
    public int ProviderId { get; set; }
    public string ProviderName { get; set; }
}

public class ProviderDBContext : DbContext
{
    public DbSet<Provider> Providers { get; set; }
}

I want whatever I enter in my view to be saved as ProviderId in my table.

Please help.

Upvotes: 2

Views: 55

Answers (1)

dfdsfdsfsdf
dfdsfdsfsdf

Reputation: 663

you need to let EF know that you want the ProviderID to be manually defined. One way is why extending EntityTypeConfiguration.

public class ProviderConfig: EntityTypeConfiguration<Provider>
    {
        public ProviderConfig()
        {
    this.Property(p => p.ProviderID)
                .HasColumnName("provider_id")
                .HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None);
}
}

Afterwards, you need to override OnModelCreating and register your configuration class.

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new ProviderConfig()); 

}

Upvotes: 1

Related Questions