使用工作单元,存储库模式更新子实体的正确方法是什么?
修改
尝试1 - 仅更新父
var existing = Find(Entry.ENTRYID);
this.UnitOfWork.Context.Entry(existing).CurrentValues.SetValues(Entry);
尝试2 - 错误 - ObjectStateManager中已存在具有相同键的对象。 ObjectStateManager无法使用相同的键跟踪多个对象。
this.UnitOfWork.Context.Entry(Entry).State = EntityState.Modified;
尝试3 - 工作但很难看。还有其他/更好的方法吗?
var existing = Find(Entry.ENTRYID);
// update parent Entry
this.UnitOfWork.Context.Entry(existing).CurrentValues.SetValues(Entry);
foreach (var existingProject in existing.Projects)
{
var newProject = Entry.Projects.SingleOrDefault(p => p.DATE_WORKED == existingProject.DATE_WORKED);
if (newProject != null)
{
existingProject.HOURS = newProject.HOURS;
//... continue updating other properties
}
}
工作单元
public class EFUnitOfWork : IUnitOfWork
{
public DbContext Context { get; set; }
public EFUnitOfWork()
{
Context = new MyEntities();
}
public void Commit()
{
Context.SaveChanges();
}
}
存储库
public class EFRepository<T> : IRepository<T> where T : class
{
public IUnitOfWork UnitOfWork { get; set; }
private IDbSet<T> _objectset;
private IDbSet<T> ObjectSet
{
get
{
if (_objectset == null)
{
_objectset = UnitOfWork.Context.Set<T>();
}
return _objectset;
}
}
}
public interface IEntryEntityRepository : IRepository<EntryEntity>
{
void SubmitChanges();
void InsertOrUpdate(EntryEntity Entry);
}
public class EntryEntityRepository : EFRepository<EntryEntity>, IEntryEntityRepository
{
public void SubmitChanges()
{
this.UnitOfWork.Commit();
}
public void InsertOrUpdate(EntryEntity Entry)
{
if (Entry.ENTRYID == default(int))
{
// New entity
this.Add(Entry);
}
else
{
// Existing entity
var existing = Find(Entry.ENTRYID);
// WORKS - updates parent Entry
this.UnitOfWork.Context.Entry(existing).CurrentValues.SetValues(Entry);
// HOW DO I UPDATE CHILD ENTITY Projects?
foreach (var existingProject in existing.Projects)
{
var newProject = Entry.Projects.SingleOrDefault(p => p.DATE_WORKED == existingProject.DATE_WORKED);
if (newProject != null)
{
WORKS --> //existingProject.HOURS = newProject.HOURS;
DOESN'T --> WORK //this.UnitOfWork.Context.Entry(existingTimeEntry).CurrentValues.SetValues(newTimeEntry);
}
}
}
}
}
实体
public partial class EntryEntity
{
public EntryEntity()
{
this.Projects = new HashSet<ProjectEntity>();
}
public int ENTRYID { get; set; }
public virtual ICollection<ProjectEntity> Projects { get; set; }
}
public partial class ProjectEntity
{
public int OBJECTID { get; set; }
public int ENTRYID { get; set; }
public System.DateTime DATE_WORKED { get; set; }
public double HOURS { get; set; }
public virtual EntryEntity Entry { get; set; }
}