【发布时间】:2018-05-17 15:55:03
【问题描述】:
如果这个问题已经在其他地方得到回答,我很抱歉;但我在这件事上发现了很多好坏参半的结果。
我正在使用:
- .net 框架 4.6.1
- Microsoft.AspNet.Mvc 5.2.6
- AutoMapper 6.2.2
- EntityFramework 6.2.0
我对 ASP.net 和 C# 都很陌生,最近我成为 AutoMapper 包的粉丝。我主要使用它来将我从ApplicationDbContext 获得的实体转换为我的DTO(数据传输对象)或ViewModel。
我现在在我的应用程序中使用此设置来初始化并在我的Controller 中使用Mapper:
Global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
Mapper.Initialize(AutoMapperConfiguration.Configure);
// Other configuration for MVC application...
}
}
AutoMapperConfiguration.cs
public static class AutoMapperConfiguration
{
public static void Configure(IMapperConfigurationExpression config)
{
config.CreateMap<Post, Post.DetailsViewModel>().ForMember(post => post.CanEdit, cfg => cfg.ResolveUsing((src, dst, arg3, context) => context.Options.Items["UserId"]?.ToString() == src.UserId));
}
}
PostsController.cs 和 Post.cs
public class PostsController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Post post = db.Posts.Find(id);
if (post == null)
{
return HttpNotFound();
}
return View(Mapper.Map<Post.DetailsViewModel>(post, options => options.Items["UserId"] = User.Identity?.GetUserId()));
}
}
// Post.cs
public class Post
{
public int Id { get; set; }
public string UserId { get; set; }
public virtual ApplicationUser User { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime PostedAt { get; set; } = DateTime.Now;
public class DetailsViewModel
{
public int Id { get; set; }
public string UserId { get; set; }
public ApplicationUser User { get; set; }
public string Title { get; set; }
public string Content { get; set; }
/// <summary>
/// A value indicating whether the current logged in user can edit the model
/// </summary>
public bool CanEdit { get; set; }
public DateTime PostedAt { get; set; }
}
}
代码摘要
我在一个静态类 (AutoMapperConfiguration) 中配置我的 Mapper,该类包含一个从 Global.asax.cs 文件调用并映射所需类的 Config 方法。
然后,在我的Controller 中,我使用静态方法Mapper.Map 将我的Post 映射到它的DetailsViewModel。
问题
AutoMapper 的这种用法(通过静态方法 Mapper.Map)如何影响性能,有没有更好的方法来做到这一点?
一些澄清:
例如:如果我在不同的控制器操作上每秒收到 100 个请求怎么办?据我所知,每个请求都会有一个单独的线程,但会为 Mapper.Map 方法访问相同的内存(如果我是正确的)。据我所知,这意味着性能将受到严重影响。
我已经看过一个问题,但得到的结果好坏参半:
Non-static AutoMapper and ASP.NET MVC -> Where to place AutoMapper.CreateMaps?
如果我在这方面有任何错误,请纠正我。
【问题讨论】:
标签: c# asp.net asp.net-mvc entity-framework automapper