[英]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.