I have not run into this before, because I usually handled collections by them selves instead of modifying them directly on the entity.
public class Schedule: BaseEntity
{
public Guid Id {get;set;}
public virtual int? DayOfTheWeekTypeId { get; set; }
public virtual DayOfTheWeekType DayOfTheWeekType { get; set; }
public virtual ICollection<Instructor> Instructors { get; set; }
public DateTime? StartDateTime { get; set; }
public DateTime? EndDateTime { get; set; }
public string SpecialInstructions { get; set; }
}
Mapping class:
public ScheduleMapping()
{
HasMany(c => c.Instructors).WithMany().Map(m => { m.MapLeftKey("ScheduleId");
m.MapRightKey("InstructorId");
m.ToTable("Schedule_Instructors");
});
HasOptional(s => s.DayOfTheWeekType).WithMany().HasForeignKey(s => s.DayOfTheWeekTypeId).WillCascadeOnDelete(false);
Property(s => s.SpecialInstructions).IsMaxLength();
}
This is my update method:
public virtual void Update(TEntity entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
//this is the original persisted entity
var persistedEntity = _repository.GetById(entity.Id);
if(originalEntity != null)
{
entity.Id = persistedEntity.Id;
UnitOfWork.ApplyCurrentValues<TEntity>(originalEntity,entity);
UnitOfWork.Commit();
}
}
This is the Method that handled the "merge"
public void ApplyCurrentValues<TEntity>(TEntity original, TEntity current) where TEntity : class
{
base.Entry<TEntity>(original).CurrentValues.SetValues(current);
}
If I modify the Instructors collection then try to apply the update, it seems to keep my original values. I have tried loading the the Schedule entity prior to the update and make my changes, but sometimes that causes a PK error (on the Instructors collection) in entity framework. As if it is trying to add an entity with the same key. So, instead I am rebuilding the Schedule entity (including the ID) manually and then updating it. When I do that I do not get any more errors, however, the Instructors collections doesn't change. I am thinking because CurrentValues. SetValues is being applied based on the persisted entity and not my updated version. the Should I handle my updates differently or do I need to manully
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…