![](/img/trans.png)
[英]How to configure Automapper to automatically ignore properties with ReadOnly attribute?
[英]Automapper ignore readonly properties
我正在尝试从一个对象映射到另一个具有公共只读Guid Id的对象,我想忽略它。 我试过这样的:
Mapper.CreateMap<SearchQuery, GetPersonsQuery>()
.ForMember(dto => dto.Id, opt => opt.Ignore());
这似乎失败了因为Id是只读的:
AutoMapperTests.IsValidConfiguration threw exception:
System.ArgumentException: Expression must be writeable
有没有办法解决?
我不认为AutoMapper支持ReadOnly字段。 只有我可以让它工作的方法是用只有一个getter的属性包装readonly字段:
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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.