【发布时间】: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