the*_*son 5 c# asp.net-mvc entity-framework entity-framework-5
我在使用EF Codefirst正确保存多对多关系时遇到问题.我已正确建模我的类并使用Fluent-API正确建模连接表.我认为这个问题与使用断开连接的DTO有关.当我将更改保存到父实体(公寓)时,父实体(例如Title和UserId)上的scalular属性保存正确,但对子实体(设施)的更改不会保存到多对多表.
这是有助于澄清事物的代码流:
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;
}
Run Code Online (Sandbox Code Playgroud)
我能够通过创建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);
}
Run Code Online (Sandbox Code Playgroud)
但是,是否有更好的方法来执行此操作,这是通用的,并且每次我需要保存多对多关系时不需要我创建自定义"更新"方法?这个/sf/answers/781851521/答案有助于澄清我认为问题所在,但我不确定如何实现更通用的方法.
谢谢你,杰森
| 归档时间: |
|
| 查看次数: |
3445 次 |
| 最近记录: |