【问题标题】:Why Automapper not working for base & inherited classes为什么 Automapper 不适用于基类和继承类
【发布时间】:2016-09-17 07:21:20
【问题描述】:

在 MVC 应用程序中,有一个 Student 类继承自 ApplicationUser 基类(ASP.NET 标识),其中有一个 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
}

我使用以下方法通过在控制器中将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              
}

使用这个方法的时候遇到错误:

方法“UserManagerExtensions.Update(UserManager, TUser)”的类型参数无法从用法中推断出来。尝试明确指定类型参数。

有解决办法吗?

【问题讨论】:

  • @BalagurunathanMarimuthu 你有什么想法吗?

标签: c# asp.net-mvc asp.net-identity automapper automapper-5


【解决方案1】:

您遇到的错误与AutoMapper 无关。

问题在于您的 student 变量的类型为 object,原因是以下行

var student = (Object)null;

虽然应该是Student

要么删除上面的行并使用

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

或者改成

Student student = null;

【讨论】:

  • 非常感谢您的回复。我尝试使用 Student student = null; 但在这种情况下,student = Mapper.Map(model); 行之后的学生属性为空。有什么错误吗?另一方面,当我使用继承时,是否有另一种使用 Automapper 中的基类/继承类映射的解决方案?
  • Mapper.Map的结果与接收变量的类型无关。现在,当您的代码编译时,您似乎遇到了映射问题。我会检查.ForAllOtherMembers(opts =&gt; opts.Ignore()) 呼叫 - 在我看来,您忽略(而不是映射)StudentViewModel 的所有成员,请考虑删除该呼叫。
  • 是的,你是对的。我忽略了“找到未映射的成员”中指示的相关属性。错误。然而,尽管新数据正确填充了学生变量,但即使没有错误,UserManager.Update(student) 也无法更新学生。我还尝试使用 Student 类的 ApplicationUser insted,因为它继承自 ApplicationUser,但它没有任何意义,并且记录没有更新。有什么想法吗?
  • 不使用 AutoMapper 解决问题怎么样?你能看看Updating user by UserManager.Update() in ASP.NET Identity 2吗?
  • 你有什么想法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-14
  • 2022-12-11
  • 1970-01-01
  • 1970-01-01
  • 2017-01-24
  • 2016-06-28
  • 1970-01-01
相关资源
最近更新 更多