使用属性在自动映射中保留目标对象 ID 字段

问题描述 投票:0回答:1

我有一个班级客户

public class Customer {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Phone { get; set; }
    public DateTime CreatedAt { get; set; }
}

我还有另一个类 CustomerSetting

[AutoMap(typeof(Customer), ReverseMap = true)]
public class CustomerSetting {
    public int Id { get; set; }
    public string Name { get; set; }
    public int UserId { get; set; }
    public string DeliveryAddress { get; set; }
    public DateTime CreatedAt { get; set; }
}

在另一个文件

service.cs
中,我定义了操作和映射。

public CustomerSetting getMappedData(){
    var customerModel = _service.getCustomer();
    var customerSetting = _service.getCustomerSetting();
    
    _mapper.map<Customer, CustomerSetting>(customerModel, customerSetting); 
}

我面临的问题是,CustomerSetting.Id 被 Customer.Id 覆盖。 如何使用属性来防止它。

到目前为止,我尝试在字段顶部使用

[Ignore]
[IgnoreMap]
,但它将值设置为默认值,即 0。

c# asp.net-core automapper
1个回答
0
投票

您可以使用控制台应用程序尝试这个简单的测试。

    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    [AutoMap(typeof(Customer), ReverseMap = true)]
    public class CustomerSetting
    {
        [Ignore]
        public int Id { get; set; }
        public string Name { get; set; }
        public int UserId { get; set; }
    }

程序.cs

var configuration = new MapperConfiguration(cfg => cfg.AddMaps("ConsoleApp47"));  //Assembly Name same as project name
var mapper = new Mapper(configuration);

var customerModel = new Customer { Id = 1, Name = "tom" };
var customerSetting = new CustomerSetting { Id = 3, UserId = 13 };

mapper.Map<Customer, CustomerSetting>(customerModel, customerSetting);

Console.WriteLine(JsonSerializer.Serialize(customerSetting));

测试结果

© www.soinside.com 2019 - 2024. All rights reserved.