簡體   English   中英

自動映射器和開放泛型

[英]Automapper and Open Generics

我正在嘗試使用https://github.com/AutoMapper/AutoMapper/wiki/Open-Generics中所述的Automapper的Open Generics執行用戶和帳戶之間的映射。

public class User
{
    public Guid UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime Dob { get; set; }
}

public class Account
{
    public Guid UserId { get; set; }
    public string FirstName { get; set; }
}

我創建了源和目標

public class Source<T>
{
    public T Value { get; set; }
}

public class Destination<T>
{
    public T Value { get; set; }
}

我想在AccountService中執行映射

public class AccountService
{
    private User user1 = new User{FirstName = "James", LastName = "Jones", Dob = DateTime.Today, UserId = new Guid("AC482E99-1739-46FE-98B8-8758833EB0D2")};

    static AccountService()
    {
        Mapper.CreateMap(typeof(Source<>), typeof(Destination<>));
    }

    public T GetAccountFromUser<T>()
    {
        var source = new Source<User>{ Value = user1 };
        var destination = Mapper.Map<Source<User>, Destination<T>>(source);
        return destination.Value;
    }
}

但是我有一個例外

缺少類型映射配置或不支持的映射。

映射類型:用戶->帳戶OpenGenerics.Console.Models.User-> OpenGenerics.Console.Models.Account

目標路徑:Destination`1.Value.Value

源值:OpenGenerics.Console.Models.User

我在https://github.com/AutoMapper/AutoMapper/wiki/Open-Generics中確認了該方法可用於intdouble

編輯這可能對我來說是一個解決方案,但是有點混亂。

    var mappingExists = Mapper.GetAllTypeMaps().FirstOrDefault(m => m.SourceType == typeof (User) && m.DestinationType == typeof (T));
    if (mappingExists == null)
        Mapper.CreateMap<User, T>();

對於封閉的泛型,還必須能夠映射類型參數。 添加:

Mapper.CreateMap<User, Account>();

而且您已設定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM