2014-01-15 152 views
0

類型基本上我有實體:AutoMapper和繼承:解決由子字符串屬性

public abstract class SocialNetworkAccount 
    { 
     public virtual string AccessToken { get; set; } 
     public virtual string ProviderUserId { get; set; } 
     public virtual string UserName { get; set; } 
    } 

和子類:

public class FacebookAccount : SocialNetworkAccount 
    { 
     public virtual string Name { get; set; } 
     public virtual string Link { get; set; } 
     public virtual GenderEnum Gender { get; set; } 
    } 
public class LinkedInAccount : SocialNetworkAccount 
{ 
    public virtual string LastName { get; set; } 
    public virtual string FirstName { get; set; } 
} 

,我需要映射DotNetOpenAuth.AspNet.AuthenticationResult我的實體。

AuthenticationResult具有字符串屬性Provider

AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication("..."); 
SocialNetworkAccount account = AutoMapper.Mapper.Map<SocialNetworkAccount>(result); 

,但我需要的實例是FacebookAccountLinkedInAccount依賴result.Provider。 任何幫助

+0

究竟'Provider'字符串包含?類型名稱? –

+0

包含像「臉譜」一樣的字符串 – Roar

回答

1

您應該手動處理提供者值。我建議你從AuthenticationResult創建映射到你需要的每個社交網絡賬戶類型。然後,只需調用擴展方法相應的映射:

public static SocialNetworkAccount ToSocialNetworkAccount(
    this AuthenticationResult result) 
{ 
    switch(result.Provider) 
    { 
     case "facebook": return Mapper.Map<FacebookAccount>(result); 
     case "linkedin": return Mapper.Map<LinkedInAccount>(result); 
     // ... 
     default: 
      throw new ArgumentException("Unknown provider: " + result.Provider); 
    } 
} 

用法:

AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication("..."); 
SocialNetworkAccount account = result.ToSocialNetworkAccount();