【问题标题】:How to store data from form with dropdown using enum如何使用枚举使用下拉列表存储表单中的数据
【发布时间】:2019-03-27 19:09:18
【问题描述】:

我正在尝试使用实体框架将详细信息从表单存储到数据库,我正在使用枚举来存储下拉内容。提交时我遇到了问题。 问题: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; }
              }
             }

【问题讨论】:

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


【解决方案1】:

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

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

希望对你有所帮助..

【讨论】:

  • 公共部分类 socialwebsiteEntities : DbContext { public socialwebsiteEntities() : base("name=socialwebsiteEntities") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity().ToTable( “社交网络表”);抛出新的 UnintentionalCodeFirstException(); } 公共虚拟 DbSet socialwebtables { 获取;放; } } }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-11
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-04
相关资源
最近更新 更多