如何使用枚举从下拉菜单中存储表单数据

时间:2019-03-27 19:09:18

标签: c# entity-framework model-view-controller enums dropdown

我正在尝试使用实体框架将详细信息从表单存储到数据库,我正在使用枚举存储下拉内容。提交时我遇到了问题。 问题:System.InvalidOperationException:'实体类型socialwebtable不是当前上下文模型的一部分。'

      [HttpPost]
     public ActionResult register(socialwebtable c1)
    {
        socialwebsiteEntities db = new socialwebsiteEntities();

        //data1 is a table name
        socialwebtable data23 = new socialwebtable();
        data23.name = c1.name;
        data23.bloodgroup = c1.bloodgroup;
        data23.city = c1.city;
        data23.phonenumber = c1.phonenumber;
        db.socialwebtables.Add(data23);
     //   db.socialwebtables.InsertOnSubmit(data23);
        db.SaveChanges();
        return View();
    }

查看:

          <div class="form-group">
          @Html.LabelFor(model => model.bloodgroup, htmlAttributes: new { 
          @class = "control-label col-md-2" })
          <div class="col-md-10">
            @Html.EnumDropDownListFor(
             x => x.bloodgroup,
             "Select My Type",
             new { @class = "form-control" })
             @Html.ValidationMessageFor(model => model.bloodgroup, "", new { 
            @class = "text-danger" })
           </div>
           </div>

型号:

              public enum enum1
                 {
             [Display(Name = "O+")]
              O,
             [Display(Name = "A+")]
              B,
             [Display(Name = "B+")]
              A,
             [Display(Name = "AB+")]
              AB,
             [Display(Name = "O-")]
              O1,
             [Display(Name = "A-")]
              B1,
             [Display(Name = "B-")]
              A1,
             [Display(Name = "AB-")]
             AB1,
               }
            public partial class socialwebtable
             {
            public int id { get; set; }
            public string name { get; set; }
            public enum1 bloodgroup { get; set; }
            public string  city  { get; set; }
            public decimal phonenumber { get; set; }
              }
             }

1 个答案:

答案 0 :(得分:0)

如果在启动时未创建表,则会发生此错误。请在您的自定义 DBContext 类中放置以下代码,以解决该问题。

protected void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Estate>().ToTable("socialwebtable");
}

希望这对您有所帮助。