【发布时间】:2019-02-21 10:58:52
【问题描述】:
我接手了一个使用 EF6、存储库模式、工作单元的 MVC Web 项目。我刚开始学习 EF6。
我想创建一个新组织并将其保存到数据库中,然后获取新的组织 ID。新的组织 ID 将用于重命名将存储在 organization.logo 中的图像文件。然后使用新文件名更新数据库中的组织徽标字段。
我保存了组织,获取了新的组织 ID,重命名了文件,但我无法更新徽标字段?
代码如下:
组织控制器 - 显示基本代码 我已经删除了很多验证和重命名图像文件。
public ActionResult Create(OrganisationViewModel viewModelToCreate)
{
Organisation newOrganisation = new Organisation();
newOrganisation.Name = viewModelToCreate.Name;
newOrganisation.Logo = "To Change";
_Uow.OrganisationRepository.InsertOrUpdate(newOrganisation);
if (ModelState.IsValid)
{
_Uow.Save();
int newOrganisationId = _Uow.OrganisationRepository.LastInsertedID();
Organisation organisationToUpdate = _Uow.OrganisationRepository.Find(newOrganisationId);
string fileName = newOrganisationId.ToString() + Path.GetExtension(viewModelToCreate.FileNameToAdd.FileName);
organisationToUpdate.Logo = fileName;
_Uow.OrganisationRepository.InsertOrUpdate(organisationToUpdate);
_Uow.Save();
}
}
public virtual T InsertOrUpdate(T e)
{
DbSet<T> dbSet = Context.Set<T>();
DbEntityEntry<T> entry;
if (e.ID != default(int))
{
entry = Context.Entry(e);
}
else
{
T instance = dbSet.Create();
instance.ID = e.ID;
entry = Context.Entry(instance);
dbSet.Attach(instance);
entry.CurrentValues.SetValues(e);
e = instance;
}
entry.State = e.ID == default(int) ?
EntityState.Added :
EntityState.Modified;
return e;
}
int IUnitOfWork.Save()
{
return _Context.SaveChanges();
}
public int LastInsertedID()
{
Context = new aContext();
int newOrganisationId = Context.Organisations.OrderByDescending(x => x.ID).FirstOrDefault().ID;
return newOrganisationId;
}
如何使用新文件名更新 organizationToUpdate.Logo,它不会保存到数据库中?
【问题讨论】:
-
为什么不设置
newOrganisation.Logo? -
我试过了,还是不行。
-
什么不起作用?很难想象这会插入一个没有徽标的
Organisation。 -
更新我的代码以回复@GertArnold 谢谢。
-
能否展示repo.InsertOrUpdate和uow.Save的代码?
标签: entity-framework-6 repository-pattern unit-of-work