This code saves an DomainEntityRecord
(parent) and DomainEntityDetailRecords
(child), and it works. It feels odd that I get the record from the DB, then remove the entities that don't exist in the domain model version, then when I save, I save (AddOrUpdate
) the domain entities, and not the EF version. Maybe this is the right way?
public void Handle(SaveDomainEntity message)
{
var domainEntityRecord = mapper.Map<DomainEntityRecord>(message);
var existingDomainEntity = dbContext.Set<DomainEntityRecord>()
.Where(x => x.Id == domainEntityRecord.Id)
.Include(x => x.DomainEntityDetailRecords)
.SingleOrDefault();
if (existingDomainEntity != null)
{
// Delete detail records that no longer exist.
foreach (var existingDetail in existingDomainEntity.DomainEntityDetailRecords.ToList())
{
if (domainEntityRecord.DomainEntityDetailRecords.All(
x => x.DetailId != existingDetail.DetailId))
{
dbContext.Set<DomainEntityDetailRecord>().Remove(existingDetail);
}
}
}
dbContext.Set<DomainEntityRecord>().AddOrUpdate(domainEntityRecord);
domainEntityRecord.DomainEntityDetailRecords.ForEach(
record => dbContext.Set<DomainEntityDetailRecord>().AddOrUpdate(record));
dbContext.SaveChanges();
}