Automapper忽略只读属性 [英] Automapper ignore readonly properties

查看:1190
本文介绍了Automapper忽略只读属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图映射从一个对象到另一个具有公共只读的Guid标识,我想忽略。我曾尝试这样的:

I'm trying to map from one object to another that has a public readonly Guid Id, which I want to ignore. I have tried like this:

Mapper.CreateMap<SearchQuery, GetPersonsQuery>()
              .ForMember(dto => dto.Id, opt => opt.Ignore());

这似乎失败,因为编号是只读的:

This seems to fail because Id is readonly:

AutoMapperTests.IsValidConfiguration threw exception: 
System.ArgumentException: Expression must be writeable

有没有解决这个办法吗?

Is there any way around this?

推荐答案

我不认为只读域由AutoMapper支持。只有这样我可以得到它的工作是与属性来包装只读域只有一个getter:

I don't think ReadOnly fields are supported by AutoMapper. Only way I could get it to work was to wrap the readonly field with a property with only a getter:

class Program
{
    static void Main()
    {
        Mapper.CreateMap<SearchQuery, GetPersonsQuery>();

        var source = new SearchQuery {Id = Guid.NewGuid(), Text = Guid.NewGuid().ToString() };

        Console.WriteLine("Src: id = {0} text = {1}", source.Id, source.Text);

        var target = Mapper.Map<SearchQuery, GetPersonsQuery>(source);

        Console.WriteLine("Tgt: id = {0} text = {1}", target.Id, target.Text);

        Console.ReadLine();
    }
}

internal class GetPersonsQuery
{
    private readonly Guid _id = new Guid("11111111-97b9-4db4-920d-2c41da24eb71");

    public Guid Id { get { return _id; } }
    public string Text { get; set; }
}

internal class SearchQuery
{
    public Guid Id { get; set; }
    public string Text { get; set; }
}

这篇关于Automapper忽略只读属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆