简体   繁体   English

为什么Automapper无法用于基类和继承的类

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

In an MVC application, there is a Student class inherited from ApplicationUser base class (ASP.NET Identity) and there is a ViewModel of it called StudentViewModel as shown below: 在MVC应用程序中,有一个从ApplicationUser基类(ASP.NET Identity)继承的Student类,并且有一个名为StudentViewModelViewModel ,如下所示:

Entity Classes: 实体类别:

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: ViewModel:

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

I use the following method in order to update a Student by mapping StudentViewModel to ApplicationUser in the Controller: 我使用以下方法通过在控制器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              
}

When using this method, I encounter an error: 使用此方法时,遇到错误:

The type arguments for method 'UserManagerExtensions.Update(UserManager, TUser)' cannot be inferred from the usage. 无法从用法中推断出方法'UserManagerExtensions.Update(UserManager,TUser)'的类型参数。 Try specifying the type arguments explicitly. 尝试显式指定类型参数。

Any idea to fix it? 有解决的办法吗?

The error you are getting has nothing to do with AutoMapper . 您遇到的错误与AutoMapper无关。

The problem is that your student variable is of type object due to the following line 问题是由于以下行,您的student变量属于object类型

var student = (Object)null;

while it should be Student . 而应该是Student

Either remove the above line and use 删除上面的行并使用

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

or change it to 或将其更改为

Student student = null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM