2016-05-05 30 views
2

我有一個mvc5應用程序,我試圖在我的模型中創建新行。 但是表的主鍵總是在一個序列中。MVC5主鍵總是需要序列

但我希望我給出的關鍵是用作主鍵。 我是新來的MVC,我不知道我在做什麼錯在這裏。

這是我的控制器

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

我可以看到,在調試中提供該值是從視圖我輸入。

這裏是我的我的部分觀點:

<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> 

這裏是我的模型類:

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

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

我想無論我在我看來進入了我的表保存爲ProviderId。

請幫忙。

回答

1

您需要讓EF知道您需要手動定義ProviderID。一種方法是爲什麼擴展EntityTypeConfiguration。

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

之後,您需要重寫OnModelCreating並註冊您的配置類。

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

} 
+0

工作就像一個魅力!謝謝 – sunny