2016-09-17 52 views
0

在MVC應用程序中,有來自ApplicationUser基類繼承一個學生類(ASP.NET身份),並有一種叫StudentViewModel一個ViewModel如下圖所示:爲什麼Automapper不工作的基礎和繼承類

實體類:

public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, 
            ApplicationUserRole, ApplicationUserClaim>, IUser<int> 
{ 
    public string Name { get; set; } 
    public string Surname { get; set; } 
    //code omitted for brevity 
} 

public class Student: ApplicationUser 
{  
    public int? Number { get; set; } 
} 

視圖模型:

public class StudentViewModel 
{ 
    public int Id { get; set; }  
    public int? Number { get; set; } 
    //code omitted for brevity 
} 

我使用下面的方法,以便在控制器更新由映射StudentViewModel一個學生ApplicationUser

[HttpPost] 
[ValidateAntiForgeryToken] 
public JsonResult Update([Bind(Exclude = null)] StudentViewModel model) 
{ 
    //Mapping StudentViewModel to ApplicationUser :::::::::::::::: 
    var student = (Object)null; 

    Mapper.Initialize(cfg => 
    { 
     cfg.CreateMap<StudentViewModel, Student>() 
      .ForMember(dest => dest.Id, opt => opt.Ignore()) 
      .ForAllOtherMembers(opts => opts.Ignore()); 
    }); 

    Mapper.AssertConfigurationIsValid(); 
    student = Mapper.Map<Student>(model); 
    //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: 

    //Then I want to pass the mapped property to the UserManager's Update method: 
    var result = UserManager.Update(student); 

    //code omitted for brevity    
} 

使用此方法時,我會遇到一個錯誤:

The type arguments for method 'UserManagerExtensions.Update(UserManager, TUser)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

任何主意修理它?

+0

@BalagurunathanMarimuthu你有什麼想法? –

回答

1

您收到的錯誤與AutoMapper無關。

的問題是,你student變量是object型由於以下行

var student = (Object)null; 

,而應該是Student

請刪除上述行並使用

var student = Mapper.Map<Student>(model); 

或將其更改爲

Student student = null; 
+0

非常感謝您的回覆。我嘗試使用** Student student = null; **,但在這種情況下,學生屬性在** student = Mapper.Map (model); ** line後爲空。有什麼錯誤嗎?另一方面,當我使用繼承時,可能會有另一種解決方案使用Automapper中的基類/繼承類的映射? –

+0

Mapper.Map的結果與接收變量的類型無關。現在,當您編寫代碼時,您似乎有一個映射問題。我會檢查'.ForAllOtherMembers(opts => opts.Ignore())'調用 - 這聽起來是你忽略了(不映射)'StudentViewModel'的所有成員,請考慮刪除該調用。 –

+0

是的,你是對的。我忽略了「找到未映射成員」中指出的相關屬性。錯誤。但是,雖然學生變量已正確填充新數據,但即使沒有錯誤,** UserManager.Update(student)**也不能更新學生。我也嘗試使用** ApplicationUser ** insted Student類,因爲它從ApplicationUser繼承,但沒有任何意義,記錄也沒有更新。任何想法? –