【发布时间】:2014-02-11 17:57:29
【问题描述】:
我在获取多对多关系以使用 EF Codefirst 正确保存时遇到问题。我已经正确地为我的类建模并使用 Fluent-API 正确地为连接表建模。我认为这个问题与使用断开连接的 DTO 有关。当我保存对父实体 (Condo) 的更改时,父实体(例如 Title 和 UserId)上的标量属性会正确保存,但对子实体 (Amenities) 的更改不会保存到多对多表中。
这是有助于澄清事情的代码流:
public ICommandResult Execute(CreateOrUpdateCondoCommand command)
{
ICollection<Amenity> amenities = new List<Amenity>();
foreach (var item in command.Amenities)
{
Amenity amenity = new Amenity { AmenityId = item.AmenityId };
amenities.Add(amenity);
}
var condo = new Condo
{
[...other properties]
Title = command.Title,
Amenities = amenities
};
if (condo.CondoId == 0)
{
condoRepository.Add(condo);
}
else
{
condoRepository.Update(condo);
}
unitOfWork.Commit();
return new CommandResult(true);
}
/// <summary>
/// Updates the entity.
/// </summary>
/// <param name="entity">The entity</param>
public virtual void Update(T entity)
{
dbset.Attach(entity);
dataContext.Entry(entity).State = EntityState.Modified;
}
我能够通过创建 condoRepository.UpdateCondo(condo) 方法来让事情正常进行,如下所示:
/// <summary>
/// Method for updating a condo
/// </summary>
/// <param name="condo">The condo to update</param>
public void UpdateCondo(Condo condo)
{
var updatedCondo = this.DataContext.Set<Condo>().Include("Amenities")
.Single(x => x.CondoId == condo.CondoId);
// Set the attributes
[other properties here...]
updatedCondo.Title = condo.Title;
updatedCondo.Amenities.Clear();
foreach (var amenity in condo.Amenities)
{
var amenityToAttach = this.DataContext.Amenities.Single(x => x.AmenityId == amenity.AmenityId);
updatedCondo.Amenities.Add(amenityToAttach);
}
this.Update(updatedCondo);
}
但是,是否有更好的通用方法来执行此操作,并且不需要我每次需要保存多对多关系时都创建自定义“更新”方法?这个https://stackoverflow.com/a/11169307/3221076 的答案有助于澄清我认为的问题所在,但我不确定如何实施更通用的方法。
谢谢, 杰森
【问题讨论】:
标签: c# asp.net-mvc entity-framework entity-framework-5