entity-framework - 为什么 automapper 使 Entity Framework 插入而不是更新?

标签 entity-framework automapper poco

我有一个 Customers 表,其中包含对 Addresses 表的外部引用。 AutoMapper 似乎正在做一些事情让 EF 认为我的地址引用是一条新记录而不是更新现有记录。

这段代码正确地更新了地址记录。它不会添加新的:

using (CSIntUnitOfWork uow = new CSIntUnitOfWork())
{
    CustomerRepository customerRepository = new CustomerRepository(uow, _resellerID);

    DataModels.Customer updateCustomer = customerRepository.GetByID(customer.CustomerID);

    updateCustomer.ResellerID = customer.ResellerID;
    updateCustomer.CustomerType = customer.CustomerType;
    updateCustomer.Password = customer.Password;
    updateCustomer.Comments = customer.Comments;

    updateCustomer.Address.ResellerID = customer.Address.ResellerID;
    updateCustomer.Address.AddressCode = customer.Address.AddressCode;
    updateCustomer.Address.AddressType = customer.Address.AddressType;
    updateCustomer.Address.CompanyName = customer.Address.CompanyName;
    updateCustomer.Address.LastName = customer.Address.LastName;
    updateCustomer.Address.FirstName = customer.Address.FirstName;

    uow.SaveChanges();
}

此代码将始终添加新的地址记录:

using (CSIntUnitOfWork uow = new CSIntUnitOfWork())
{
    CustomerRepository customerRepository = new CustomerRepository(uow, _resellerID);

    DataModels.Customer updateCustomer = customerRepository.GetByID(customer.CustomerID);

    Mapper.CreateMap<Customer, Customer>()
        .ForMember(dest => dest.CustomerID, opt => opt.Ignore());
    Mapper.Map(customer, updateCustomer);

    Mapper.CreateMap<Address, Address>()
        .ForMember(dest => dest.ID, opt => opt.Ignore());
    Mapper.Map(customer.Address, updateCustomer.Address);

    uow.SaveChanges();
}

知道为什么会这样吗?

最佳答案

我刚刚想通了。

AutoMapper 正在映射 Customers 中的所有字段,包括 Address 字段。以下代码效果很好:

using (CSIntUnitOfWork uow = new CSIntUnitOfWork())
{
    CustomerRepository customerRepository = new CustomerRepository(uow, _resellerID);

    DataModels.Customer updateCustomer = customerRepository.GetByID(customer.CustomerID);

    Mapper.CreateMap<Customer, Customer>()
        .ForMember(dest => dest.CustomerID, opt => opt.Ignore())
        .ForMember(dest => dest.Address, opt => opt.Ignore());  // <-- This was the problem!
    Mapper.Map(customer, updateCustomer);

    Mapper.CreateMap<Address, Address>()
        .ForMember(dest => dest.ID, opt => opt.Ignore());
    Mapper.Map(customer.Address, updateCustomer.Address);

    uow.SaveChanges();
}

关于entity-framework - 为什么 automapper 使 Entity Framework 插入而不是更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9135655/

相关文章:

c# - POCO 和多个 ViewModel 指向同一个 POCO?

asp.net - Linq/实体 : Everything Or Nothing (in Database)

.net - 生成数据库 - 没有执行 SQL 选项?

c# - 具有 EF 导航属性的自动映射器

c++ - 如何使用 C++ 从网页中获取文本?

.net - 使用具有 POCO 支持的 Entity Framework 4 实现 propertychanged 事件的最罕见和最有效的方法是什么?

c# - 应编译哪种类型的 Linq to SQL 查询?

c# - 没有子导航属性的 EF 一对多外键

c# - 如何使用 Unity 注册 AutoMapper 配置文件

c# - 将项目添加到新集合而不是替换整个集合