我想知道UoW模式更好一点,因为我喜欢它的概念,但目前我有一个难以节省时间的实体。工作单位/存储库模式和更新实体使用EF
的问题是,当我的控制器火灾我的编辑(POST)操作只母公司获取保存和子实体是完整的,即我得到以下错误:
Attaching an entity of type 'Access.Models.ApplicationParameter' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.
注:父实体应用程序可以有多个子实体应用程序参数实体。
控制器
[HttpPost]
public ActionResult Edit(ApplicationVM applicationVM)
{
Application application = ViewModelToModel(applicationVM);
uow.ApplicationRepository.Update(application);
foreach (var applicationParameterVM in applicationVM.ApplicationParameters)
{
ApplicationParameter applicationParameter = ViewModelToModel(applicationParameterVM);
bool exists = uow.ApplicationParameterRepository.Exists(applicationParameter.idApplicationParameter);
if (exists)
{
uow.ApplicationParameterRepository.Update(applicationParameter);
}
else
{
uow.ApplicationParameterRepository.Insert(applicationParameter);
}
}
uow.Save();
return View(applicationVM);
}
ApplicationParameterRepository.cs(刚刚更新片段)
public void Update(ApplicationParameter entity)
{
db.Entry(entity).State = EntityState.Modified;
}
UOW.cs
public class UnitOfWork : IDisposable
{
private AMEntities db = null;
public UnitOfWork()
{
db = new AMEntities();
}
//Add all the repository handles here
IApplicationRepository applicationRepository = null;
IApplicationParameterRepository applicationParameterRepository = null;
IApplicationUserRepository applicationUserRepository = null;
//Add all the repository getters here
public IApplicationRepository ApplicationRepository
{
get
{
if (applicationRepository == null)
{
applicationRepository = new ApplicationRepository(db);
}
return applicationRepository;
}
}
public IApplicationParameterRepository ApplicationParameterRepository
{
get
{
if (applicationParameterRepository == null)
{
applicationParameterRepository = new ApplicationParameterRepository(db);
}
return applicationParameterRepository;
}
}
public IApplicationUserRepository ApplicationUserRepository
{
get
{
if (applicationUserRepository == null)
{
applicationUserRepository = new ApplicationUserRepository(db);
}
return applicationUserRepository;
}
}
public void Save()
{
db.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
db.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
问题:我应该怎么做才能保存这些子实体?
这是正确的答案!忘了在这里发布解决方案,但#1是我如何解决它。问题是我从ViewModel获取没有所有信息的实体。 –