【问题标题】:Coudn't save Many-to-many code first Db无法先保存多对多代码 Db
【发布时间】:2016-12-27 12:01:31
【问题描述】:

我首先使用代码和流利的 api 这是我的模型

public Admin()
        {
            this.course = new HashSet<Courses>();
        }
   [Key]
   public int ID { get; set; }
   public string LoginName { get; set; }
   public virtual ICollection<Courses> course { get; set; }
}

 public Courses()
            {
                this.admin = new HashSet<Admin>();
            }
      [Key]
      public int ID { get; set; }
      public string Name { get; set; }
      public virtual ICollection<Admin> admin { get; set; }
    }

这是流畅的api

modelBuilder.Entity<Admin>()
                .HasMany(e => e.course)
                .WithMany(e => e.admin);

这是我的控制器,我从 cshml 获取 courseid

  public ActionResult Admins( Admin rec, IList<int> CourseId)
  {

      foreach (var item in CourseId)
        {
            var cr = new Courses();
            cr.ID = item;
            rec.course.Add(cr);
 }
  db.Admins.Add(rec);
  db.SaveChanges();

当我尝试保存 db.SaveChanges() 时出现错误

谁能告诉我这里出了什么问题?

错误信息

一个或多个实体的验证失败。有关详细信息,请参阅“EntityValidationErrors”属性

【问题讨论】:

  • 错误是什么?
  • 一个或多个实体的验证失败。有关详细信息,请参阅“EntityValidationErrors”属性。

标签: c# sql-server asp.net-mvc entity-framework ef-code-first


【解决方案1】:

问题在于 EF 假定您添加到 Admin.courseCourses 实例是新的。您需要使用DbSet&lt;T&gt;.Attach 方法或DbEntityEntry.State 属性让EF 将它们视为存在:

foreach (var item in CourseId)
{
    var cr = new Courses();
    cr.ID = item;

    // Here:
    db.Entry(cr).State = EntityState.Unchanged;

    // or alternatively:
    // db.Courses.Attach(cr);

    rec.course.Add(cr);
}
db.Admins.Add(rec);
db.SaveChanges();

【讨论】:

    猜你喜欢
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    相关资源
    最近更新 更多