C# MVC5主键始终采用顺序

C# MVC5主键始终采用顺序,c#,asp.net-mvc-5,C#,Asp.net Mvc 5,我有一个mvc5应用程序,试图在模型中创建新行。 但是表的主键总是在一个序列中 但我希望我提供的密钥用作主键。 我是MVC的新手,我不确定我在这里做错了什么 这是我的控制器 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "ProviderId,ProviderName")] Provider provider) { if (ModelSta

我有一个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);
    }
我可以看到,在调试provider时,我从视图中输入的值就是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>

@LabelFor(model=>model.ProviderId,htmlAttributes:new{@class=“controllabel col-md-2”})
@EditorFor(model=>model.ProviderId,new{htmlAttributes=new{@class=“form control”}})
@Html.ValidationMessageFor(model=>model.ProviderId,“,new{@class=“text danger”})
@LabelFor(model=>model.ProviderName,htmlAttributes:new{@class=“controllabel col-md-2”})
@EditorFor(model=>model.ProviderName,new{htmlAttributes=new{@class=“form control”}})
@Html.ValidationMessageFor(model=>model.ProviderName,“,new{@class=“text danger”})
这是我的模型课:

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

public class ProviderDBContext : DbContext
{
    public DbSet<Provider> Providers { get; set; }
}
公共类提供程序
{
[关键]
public int ProviderId{get;set;}
公共字符串提供程序名称{get;set;}
}
公共类ProviderDBContext:DbContext
{
公共数据库集提供程序{get;set;}
}
我希望在视图中输入的内容都保存为表中的ProviderId


请提供帮助。

您需要让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);
}
}

工作得很有魅力!非常感谢。
  protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new ProviderConfig()); 

}