简体   繁体   English

如何使用Automapper映射

[英]how do I map this using Automapper

I am in need to map the below scenario. 我需要映射以下情况。

public class Customer
{
    public string CustomerJson { get; set; }
}

public class CustomerTO
{
     public object CustomerJson { get; set; }
}

From DAL I get CustomerJson value as below. 从DAL中,我得到如下的CustomerJson值。

Customer.CustomerJson = {
    "name": "Ram",
    "city": "India"
}

I am in need to Deserialize this string. 我需要反序列化此字符串。 so I tried the below stuff while mapping. 因此我在映射时尝试了以下内容。

var config = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap<Customer, CustomerTO>()
                        .ForMember(dest => dest.CustName, opt => opt.MapFrom(src => JsonConvert.DeserializeObject(src.CustName)));
                    });

But this gives me run time error. 但这给了我运行时错误。

Unhandled Exception: AutoMapper.AutoMapperMappingException: Error mapping types. 未处理的异常:AutoMapper.AutoMapperMappingException:错误映射类型。

So I kept it simple. 所以我保持简单。

var config = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap<Customer, CustomerTO>()
                        .ForMember(dest => dest.CustName, opt => opt.MapFrom(src => (src.CustName));
                    });

And I tried to deserialize it while consuming. 而且我尝试在使用时反序列化它。 But this give compile time error. 但这会导致编译时错误。

var custJson = JsonConvert.DeserializeObject(customerTO.CustomerJson );

Error 2 The best overloaded method match for 'Newtonsoft.Json.JsonConvert.DeserializeObject(string)' has some invalid arguments 错误2'Newtonsoft.Json.JsonConvert.DeserializeObject(string)'的最佳重载方法匹配具有一些无效的参数

I know customerTO.CustomerJson is not string but how do should I do the required mapping? 我知道customerTO.CustomerJson不是字符串,但是我应该怎么做所需的映射?

Thanks. 谢谢。

Based on your previous question and given the information above you seem to be confusing what you're trying to do here. 根据您先前的问题,并根据上述信息,您似乎对此处的操作感到困惑。

So I'm going to amalgamate the data from both in an attempt to solve the issues. 因此,我将合并两者的数据,以解决问题。

Entity Classes: 实体类别:

public class Customer
{
    public int CustomerId {get; set; }
    public string CustomerName { get; set; }
    public string CustomerJson { get; set; }
}

public class CustomerTO
{
    public int CustId { get; set; }
    public object CustData { get; set; }
    public object CustomerJson { get; set; }
}

AppMapper Class: AppMapper类别:

public static class AppMapper
{
    public static MapperConfiguration Mapping()
    {
        return new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Customer, CustomerTO>()
                .ForMember(dest => dest.CustId, opt => opt.MapFrom(src => src.CustomerId))
                .ForMember(dest => dest.CustData, opt => opt.MapFrom(src => src.CustName))
                .ForMember(dest => dest.CustomerJson, opt => opt.MapFrom(src => JsonConvert.DeserializeObject(src.CustomerJson));
            });
    }
}

Main: 主要:

public class Program
{
    static void Main(string[] args)
    {
        var config = AppMapper.Mapping();
        var mapper = config.CreateMapper();

        // From Previous question get list of Customer objects
        var customers = AddCustomers();
        var mappedCustomers = mapper.Map<IEnumerable<CustomerTO>>(customers);
    }
}

A couple of things to point out I'm not sure what the purpose of CustData is in CustomerTO . 有两点需要指出,我不确定CustomerTOCustData的目的是什么。 It seems to be duplicating CustomerJson and if so remove it and the associated mapping. 它似乎在复制CustomerJson ,如果是这样,则将其删除以及关联的映射。

Also, you never mention mapping from DTO back to entity, but for the JsonObject you just need to configure it to map the serialized string to the appropriate Property. 另外,您永远不会提到从DTO映射回实体的映射,但是对于JsonObject,您只需要配置它即可将序列化的字符串映射到适当的Property。

This is how I addressed my requirement. 这就是我解决要求的方式。

Db Entity Db实体

public class Customer 
{
   public string CustomerData { get; set; }
   // & other properties 
}

My DTO 我的DTO

public class CustomerTO
{
   public object CustomerData { get; set;}
   // & other properties
}

I created a Utility like class with name AppMapper. 我创建了一个类似类的实用程序,名称为AppMapper。 This is how my AppMapper.cs looks like. 这就是我的AppMapper.cs的样子。

public class AppMapper
{
    private IMapper _mapper;
    public AppMapper()
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<Customer, CustomerTO>();
            //& other such mapping
        });

        _mapper = config.CreateMapper();
    }

public CustomerTO Map(Customer customerEntity)
    {
        var customerTo= _mapper.Map<Customer,CustomerTO>(customerEntity);
        return customerTo;
    }

Now when I needed the mapping. 现在,当我需要映射时。

class DAL
{
    public CustomerTO GetCustomers()
    {
        var customers= //LINQ To get customers 

        var customerTO = Mapping(customer);

        return customerTO;

    }
    //However, this mapping glue in some internal class to retain SOLID principles
    private CustomerTO Mapping(Customer custEntity)
    {
        var custTO = _appMapper.Map(custEntity);
        var str = JsonConvert.Serialize(custTO.CustomerData);
        custTO.CustomerData = JsonConvert.Deserialize(str);
        return custTO;
    }
}

That's it. 而已。

@Barry O'Kane - Sincere thanks for your inputs. @Barry O'Kane-衷心感谢您的投入。

Points to be noted:- 注意事项:

  1. I don't need to map manually any of the properites since the property name is same. 由于属性名称相同,因此不需要手动映射任何属性。 Plus I am casting string to object. 另外,我正在将字符串转换为对象。 So no issues. 所以没有问题。
  2. If you use .Map() for one property, then I found that I need to map each property else it gives default value of the data type.(Ex. for int it gives 0). 如果对一个属性使用.Map() ,那么我发现我需要映射每个属性,否则它会给出数据类型的默认值(例如,对于int来说它给出0)。

Yes. 是。 agreed there could be other method in Automapper which allows me specify that for a particulay property do this manual mapping & for rest use Automapping mechanism. 同意在Automapper中可能存在其他方法,该方法允许我指定对于特定属性执行此手动映射,而其余部分则使用Automapping机制。 But I am not sure on that. 但是我不确定。

Please feel free to improve this ans in any way. 请随时以任何方式改善此问题。

Hope this helps :) 希望这可以帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM