我在使用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)
{ …Run Code Online (Sandbox Code Playgroud)