实体框架 - 更新复杂实体

时间:2013-07-22 16:19:49

标签: c#-4.0 entity-framework-5 automapper

我正在使用EF5.0(数据库优先)并尝试更新“公司”实体这是一个复杂类型,它包含“地址”实体作为导航属性。 我从UI接收公司DTO对象,并使用AutoMapper将其映射到Entity对象并调用objectContext.Save()进行保存。

面临的问题是,“公司”实体值正在保存,而不是“地址”实体。以下是每个对象的详细信息 -

 public class CompanyDto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public AddressDto Address { get; set; }
}

使用AddressDto作为 -

public class AddressDto : IDto
{
    public int Id { get; set; }
    public string Street { get; set; }
    public string City { get; set; }
    public string PostCode { get; set; }
}

公司实体(由EF - 数据库首先生成)

 public partial class tblCompany
{
    public tblCompany()
    {
        this.tblAddresses = new HashSet<tblAddress>();
    }

    public int ID { get; set; }
    public string CompanyName { get; set; }

    public virtual ICollection<tblAddress> tblAddresses { get; set; } //navigation property
}
带有地址实体的

如下 -

  public partial class tblAddress
{
    public int ID { get; set; }
    public int CaseID { get; set; }
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string City { get; set; }
    public string County { get; set; }
    public string PostCode { get; set; }

    public virtual tblCase tblCase { get; set; }
}

AutoMapper映射配置,用于从DTO转换为实体

  Mapper.CreateMap<CompanyDto, tblCase>()
            .ForMember(x => x.ID, opt => opt.MapFrom(cd => cd.Id))
            .ForMember(x => x.CompanyName, opt => opt.MapFrom(cd => cd.Name))
            .AfterMap((s, d) => d.tblAddresses.Add(new tblAddress
            {
                AddressLine1 = s.Address.Street,
                CaseID = s.Id,
                City = s.Address.City,
                PostCode = s.Address.PostCode
            }));



 public void Update(CompanyDto company)
    {
        //TO DO: check if AutoMapper could map address as well.

        var companyDao = Mapper.Map<CompanyDto, tblCase>(company);
        _companyRepository.Update(companyDao);
        _unitOfWork.Save();
    }

提前致谢

西

0 个答案:

没有答案