I am trying to figure out best practices when updating an entity and all its children. For instance; I have an employer update service that updates the entity of the employer and the entity "Address" of the employer and the "Telephone" entities of each "Address". The user can add new addresses to the existing employer, or they can update the current addresses or delete them, the same applies to the phones of each address. Could you help me write the perfect code that will handle this script.
I am using EF7 rc1 and I am using Automapper to map Dto to Entity in my service.
public partial class Employer { public int EmployerId { get; set; } public int Name { get; set; } [InverseProperty("Employer")] public virtual ICollection<Address> Address { get; set; } } public partial class Address { public int AddressId { get; set; } public int Address1{ get; set; } public int City { get; set; } [ForeignKey("EmployerId")] [InverseProperty("Address")] public virtual Employer Employer { get; set; } [InverseProperty("Address")] public virtual ICollection<Phone> Phone { get; set; } } public partial class Phone { public int PhoneId { get; set; } public string Number { get; set; } [ForeignKey("AddressId")] [InverseProperty("Phone")] public virtual Address Address { get; set; } }
My service method;
public async Task<IServiceResult> Update(EmployerDto employer) { var employerDbEntity = await _db.Employer .Include(a=>a.Address).ThenInclude(p=>p.Phone) .SingleOrDefaultAsync (a=>a.EmployerId == employer.EmployerId);
source share