簡體   English   中英

為什么Automapper無法用於基類和繼承的類

[英]Why Automapper not working for base & inherited classes

在MVC應用程序中,有一個從ApplicationUser基類(ASP.NET Identity)繼承的Student類,並且有一個名為StudentViewModelViewModel ,如下所示:

實體類別:

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; }
}

ViewModel:

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

我使用以下方法通過在控制器StudentViewModel映射到ApplicationUser來更新Student:

[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              
}

使用此方法時,遇到錯誤:

無法從用法中推斷出方法'UserManagerExtensions.Update(UserManager,TUser)'的類型參數。 嘗試顯式指定類型參數。

有解決的辦法嗎?

您遇到的錯誤與AutoMapper無關。

問題是由於以下行,您的student變量屬於object類型

var student = (Object)null;

而應該是Student

刪除上面的行並使用

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

或將其更改為

Student student = null;

暫無
暫無

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

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