2016-09-17 81 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继承,但没有任何意义,记录也没有更新。任何想法? –