【发布时间】:2016-09-06 15:04:39
【问题描述】:
我在 MVC 项目中使用 Automapper,在该项目中我还使用 ASP.NET Identity 并从 ApplicationUser 类继承到我的自定义用户表:Student 和 Coordinator。问题是;我检索用户数据,其中有填充的自定义属性(称为 Number),但在应用 Automappe 的映射后,它只填充 ApplicationUser 中的属性,并且 Number 属性为空。是否有任何错误或如何解决?
领域模型:
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 RegisterViewModel
{
public int Id { get; set; }
public int? Number { get; set; }
//code omitted for brevity
}
控制器:
[AllowAnonymous]
[HttpGet]
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ApplicationUser user = db.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<ApplicationUser, RegisterViewModel>();
});
IMapper mapper = config.CreateMapper();
//var source = new ApplicationUser();
var dest = mapper.Map<ApplicationUser, RegisterViewModel>(user);
return PartialView("_Details", dest);
}
【问题讨论】:
-
另一件事 - 您不应该在每个控制器操作上配置 AutoMapper。 AutoMapper 配置就像 EF 配置一样 - 静态并且每个 AppDomain 定义一次。您应该在 global.asax 或类似文件中有一个 Mapper.Initialize 并初始化您的地图一次。
-
@JimmyBogard 感谢您的回复。 1) 您能否发布一个示例作为答案? 2) 我需要在Controller中将ApplicationUser转换为RegisterViewModel,在这种情况下,有什么办法可以解决这个问题吗?可以回复一下吗?
-
你能告诉我们RegisterViewModel吗?
标签: c# asp.net asp.net-mvc asp.net-identity automapper