【问题标题】:Entity Framework Code First Many-to-Many tries to create duplicates实体框架代码优先多对多尝试创建重复项
【发布时间】:2012-02-22 06:24:59
【问题描述】:

在我的应用程序中,我在 Appointments 和 AppointmentTypes 之间进行了多对多连接。创建数据库时,会创建一个名为 AppointmentTypesAppointments 的表作为连接表。

当我创建并保存具有多种约会类型的新约会时,连接表会正确填充。

但是,当我稍后编辑并重新保存约会时,未对约会类型进行任何更改,应用程序会尝试在连接表 (AppointmentTypesAppointments) 中创建重复条目。

如何阻止应用程序尝试创建这些重复行?

// appointments are fetched as a group...
using (var context = new SchedulerContext())
        {
            //return GetAll();
            IQueryable<Appointment> queryable = context.Appointments;

            // check if any records exist
            if (queryable.Count() == 0)
            {
                MessageBox.Show(@"No Appointment details found within the database");
            }

           return queryable.ToList();
        }
//-----------------------------------------
// user then edits a single appointment and it is saved as below....
using (var context = new SchedulerContext())
{
    try
    {
        var originalEntity = context.Appointments.Where(x => x.Id == id).FirstOrDefault();
        context.Entry(originalEntity).CurrentValues.SetValues(appointment);
        context.SaveChanges();
        return SuccessResult();
    }
    catch
    {
        return OtherFailResult(id);
    }
}

【问题讨论】:

  • 这个帖子很不清楚。请解释并为您的保存和获取方法添加一些代码。

标签: c# entity-framework ef-code-first


【解决方案1】:

您如何进行编辑和重新保存?很明显,EF 不知道您正在对现有实体进行更新。您需要检查是否存在以确定它是添加还是保存。

【讨论】:

  • 使用上下文(例如上下文 A)连接检索约会。然后使用新的上下文(例如上下文 B)编辑和重新保存记录。
  • ... 继续...(对不起)我使用 id 将原始记录返回到新上下文中,使用我编辑的约会更新值,然后执行 context.Save 更新所有内容其他很好,但不是约会类型集合
  • 我认为这可能是问题所在,您为什么需要两个上下文。请发布一些代码,以便我们为您提供帮助。
  • 我认为您需要将约会附加到当前上下文中,看看这个帖子blogs.msdn.com/b/adonet/archive/2011/01/29/…
  • 我添加了用于获取约会集合的代码,用户可以从中选择一个进行编辑...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-03
  • 1970-01-01
  • 1970-01-01
  • 2014-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多