【发布时间】:2013-07-31 20:29:13
【问题描述】:
我正在尝试使用实体框架在 MVC 控制器方法中添加新记录。 当我刚刚使用“InsertOrUpdate”时,审计类型被重复了。根据Entity Framework adding record with a related object 的回答,我希望能尽快修复它。这是我现在的代码:
控制器:
if (ModelState.IsValid)
{
Audit newAudit = Factory.GetNew();
newAudit.Name = model.Name;
newAudit.Deadline = model.Deadline;
newAudit.AuditType = auditTypeRepository.Find(model.SelectedAuditTypeId);
Repository.InsertOrUpdate(newAudit);
Repository.Save();
return RedirectToAction(MVC.Audits.Details(newAudit.Id));
}
存储库:
public override void InsertOrUpdate(Qdsa.WebApplications.AuditMaster.Data.Audit model)
{
if (model.Id == default(int))
{
// New entity
context.Audits.Add(model);
}
else
{
// Existing entity
model.ModifiedOn = DateTime.Now;
context.Entry(model).State = EntityState.Modified;
}
//If I leave out the code below the AuditType will be duplicated
if (model.AuditType != null)
{
context.Entry<AuditType>(model.AuditType).State = EntityState.Unchanged;
}
}
public virtual void Save()
{
context.SaveChanges();
}
所以我想我解决了这个问题。但是, AuditType 也有 Child 对象。现在这些子对象被复制了。 添加具有已存在子对象的实体的正确方法是什么? 因为 AuditType 是必需的,所以我不能先保存它,然后再更新它。有什么建议吗?
更新: AuditRepostory 和 AuditTypeRepository 都继承自 BaseRepository,其上下文为:
protected DBContext context = new DBContext ();
public virtual T Find(int id)
{
return All.SingleOrDefault(s => s.Id == id);
}
【问题讨论】:
标签: asp.net-mvc entity-framework entity-framework-5 code-first dbcontext