0

在 MVC 应用程序中,有一个继承自基ApplicationUser类(ASP.NET 标识)的 Student 类,其中有一个ViewModel调用StudentViewModel如下所示:

实体类:

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
}

我使用以下方法通过映射StudentViewModelApplicationUser控制器来更新学生:

[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)”的类型参数。尝试明确指定类型参数。

有什么想法可以解决吗?

4

1 回答 1

1

您得到的错误与AutoMapper.

问题是由于以下行,您的student变量属于类型object

var student = (Object)null;

虽然它应该是Student

删除上面的行并使用

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

或将其更改为

Student student = null;
于 2016-09-17T07:34:34.477 回答