MVC5主键始终采用序列

时间:2016-05-05 17:24:07

标签: c# asp.net-mvc-5

我有一个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 个答案:

答案 0 :(得分: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()); 

}
相关问题