前言

Hi,大家好,我是Rector

时间飞逝,一个星期又过去了,今天还是星期五,Rector在图享网继续跟大家分享系列文本:一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar]

上一篇《一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](四)》,我们完成了:

  • 创建服务层:TsBlog.Services
  • 创建服务接口
  • 实现服务接口
  • 创建仓储接口
  • 安装Autofac依赖注入组件
  • 注册配置Autofac 依赖注入

其中,最主要的是在项目中引入依赖注入组件:Autofac并配置及简单的使用。本文我们将继续本系列教程。

本文知识要点

  • AutoMapper是什么简述
  • 安装AutoMapper
  • AutoMapper的配置
  • AutoMapper的应用

AutoMapper 简述

什么是AutoMapper?

简单来说,AutoMapper是以.NET(C#)语言开发的一个轻量的处理一个实体对象到另一个实体对象之间映射关系的组件库。开发人员需要作的事则是通过AutoMapper配置两个实体对象之间的一些映射关系。

为什么使用AutoMapper?

映射代码是无聊的。测试映射代码更无聊。AutoMapper提供了一些简单配置,还有一些简单的映射测试。真正的问题可能是“为什么使用对象-对象的映射呢”?映射可能发生在一个应用的许多地方,但大多数情况下都发生在层与层之间的边界,比如UI/Domain层之间,或者Service/Domain层之间。关注一层通常和关注另一层发生冲突,因此对象-对象间的映射来隔离模型model,这样就只会影响每一层关注的类型。

安装AutoMapper

安装AutoMapper非常简单,我们可以通过Nuget命令:

PM> Install-Package AutoMapper

直接安装到对应的项目中,但在本系列的项目中,我们会专门创建一个关于AutoMapper的项目来配置AutoMapper的实体对象映射。所以,打开TsBlog解决方案,右键单击解决方案目录【1.Libraries】,添加一个新的.Net Framework项目,如下图:

选中刚才创建的项目[TsBlog.AutoMapperConfig],打开程序包管理控制台,选中默认项目为[1.Libraries\TsBlog.AutoMapperConfig],输入Nuget包安装命令,如下:

按Enter(回车)进行安装,本文写作时的AutoMapper版本是AutoMapper.6.2.2。

AutoMapper的配置

为了解决方案的目录结构更加清晰,我这里把视图实体放到了一个单独的项目中。所以,再在解决方案目录[1.Libraries]下创建一个名为[TsBlog.ViewModel]的项目,这个项目只存放关于视图实体的类文件。

为了本文的演示,在TsBlog.ViewModel项目中创建Post文件夹,再创建一个PostViewModel.cs的视图类,此时的解决方案目录为:

PostViewModel.cs :

namespace TsBlog.ViewModel.Post
{
/// <summary>
/// 博文视图实体类
/// </summary>
public class PostViewModel
{
/// <summary>
/// ID
/// </summary>
public int Id { get; set; }
/// <summary>
/// 标题
/// </summary>
public string Title { get; set; }
/// <summary>
/// 内容
/// </summary>
public string Content { get; set; }
/// <summary>
/// 作者ID
/// </summary>
public string AuthorId { get; set; }
/// <summary>
/// 作者姓名
/// </summary>
public string AuthorName { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public string CreatedAt { get; set; }
/// <summary>
/// 发布时间
/// </summary>
public string PublishedAt { get; set; }
/// <summary>
/// 是否标识已删除
/// </summary>
public string IsDeleted { get; set; }
/// <summary>
/// 是否允许展示
/// </summary>
public bool AllowShow { get; set; }
/// <summary>
/// 浏览量
/// </summary>
public int ViewCount { get; set; }
}
}

其中的属性:CreatedAt,PublishedAt,IsDeleted 类型都和领域模型Post.cs实体类中的数据类型不同了。

配置实体映射

接下来,我们回到项目[TsBlog.AutoMapperConfig]项目,在项目引用中添加如下引用:

TsBlog.Domain

TsBlog.ViewModel

再创建三个类文件,分别为:AutoMapperConfiguration.cs,AutoMapperStartupTask.cs,MappingExtensions.cs。

代码分别为:

AutoMapperConfiguration.cs

using AutoMapper;
using TsBlog.Domain.Entities;
using TsBlog.ViewModel.Post; namespace TsBlog.AutoMapperConfig
{
/// <summary>
/// AutoMapper的全局实体映射配置静态类
/// </summary>
public static class AutoMapperConfiguration
{
public static void Init()
{
MapperConfiguration = new MapperConfiguration(cfg =>
{ #region Post
//将领域实体映射到视图实体
cfg.CreateMap<Post, PostViewModel>()
.ForMember(d => d.IsDeleted, d => d.MapFrom(s => s.IsDeleted ? "是" : "否")) //将布尔类型映射成字符串类型的是/否
;
//将视图实体映射到领域实体
cfg.CreateMap<PostViewModel, Post>();
#endregion
}); Mapper = MapperConfiguration.CreateMapper();
} public static IMapper Mapper { get; private set; } public static MapperConfiguration MapperConfiguration { get; private set; }
}
}

AutoMapperStartupTask.cs

namespace TsBlog.AutoMapperConfig
{
/// <summary>
/// AutoMapper初始化类
/// </summary>
public class AutoMapperStartupTask
{
public void Execute()
{
AutoMapperConfiguration.Init();
}
}
}

MappingExtensions.cs

using TsBlog.Domain.Entities;
using TsBlog.ViewModel.Post; namespace TsBlog.AutoMapperConfig
{
/// <summary>
/// 数据库表-实体映射静态扩展类
/// </summary>
public static class MappingExtensions
{
public static TDestination MapTo<TSource, TDestination>(this TSource source)
{
return AutoMapperConfiguration.Mapper.Map<TSource, TDestination>(source);
} public static TDestination MapTo<TSource, TDestination>(this TSource source, TDestination destination)
{
return AutoMapperConfiguration.Mapper.Map(source, destination);
} #region Post
public static PostViewModel ToModel(this Post entity)
{
return entity.MapTo<Post, PostViewModel>();
} public static Post ToEntity(this PostViewModel model)
{
return model.MapTo<PostViewModel, Post>();
} #endregion }
}

到此,AutoMapper的映射配置完成。

AutoMapper的应用

初始化AutoMapper的配置

打开WEB项目[TsBlog.Frontend],引用项目[TsBlog.AutoMapperConfig],再在全局配置文件Global.asax中,添加AutoMapper的初始化方法:

/// <summary>
/// AutoMapper的配置初始化
/// </summary>
private void AutoMapperRegister()
{
new AutoMapperStartupTask().Execute();
}

同时在 Application_Start 方法中调用,此时的Global.asax文件代码如下:

using Autofac;
using Autofac.Integration.Mvc;
using System.Web.Mvc;
using System.Web.Routing;
using TsBlog.AutoMapperConfig;
using TsBlog.Repositories;
using TsBlog.Services; namespace TsBlog.Frontend
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
//BundleConfig.RegisterBundles(BundleTable.Bundles); AutofacRegister(); AutoMapperRegister();
} private void AutofacRegister()
{
var builder = new ContainerBuilder(); //注册MvcApplication程序集中所有的控制器
builder.RegisterControllers(typeof(MvcApplication).Assembly); //注册仓储层服务
builder.RegisterType<PostRepository>().As<IPostRepository>();
//注册服务层服务
builder.RegisterType<PostService>().As<IPostService>(); //注册过滤器
builder.RegisterFilterProvider(); var container = builder.Build(); //设置依赖注入解析器
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
} /// <summary>
/// AutoMapper的配置初始化
/// </summary>
private void AutoMapperRegister()
{
new AutoMapperStartupTask().Execute();
}
}
}

到此,AutoMapper的安装、配置就基本完成了,接下来我们将学习在WEB项目[TsBlog.Frontend]的控制器操作中如何使用AutoMapper。

使用AutoMapper

1.打开WEB项目[TsBlog.Frontend],添加对TsBlog.ViewModel的引用。

2.打开HomeController.cs,将代码修改为:

using System.Web.Mvc;
using TsBlog.AutoMapperConfig;
using TsBlog.Services; namespace TsBlog.Frontend.Controllers
{
public class HomeController : Controller
{
private readonly IPostService _postService;
public HomeController(IPostService postService)
{
_postService = postService;
}
public ActionResult Index()
{
return View();
} public ActionResult Post()
{
//var postRepository = new PostRepository();
//var post = postRepository.FindById(1);
//return View(post); var post = _postService.FindById(1).ToModel();
return View(post);
}
}
}

其中,我们将:

var post = _postService.FindById(1);

修改成了:

var post = _postService.FindById(1).ToModel();

再打开视图文件:~/Views/Home/Post.cshtml,将

@model TsBlog.Domain.Entities.Post

修改成:

@model TsBlog.ViewModel.Post.PostViewModel

并添加部分测试AutoMapper映射字段的代码,

此时的 Post.cs:

@model TsBlog.ViewModel.Post.PostViewModel
@{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Post find by id test</title>
</head>
<body>
<div>
<p>Post id:@Model.Id</p>
<p>Post Title:@Model.Title</p>
<p>Post PublishedAt:@Model.PublishedAt</p>
<p>Post IsDeleted:@Model.IsDeleted</p>
</div>
</body>
</html>

打开数据库,确保PublishedAt字段中值。

再次按F5运行,打开页面[http://localhost:54739/home/post]

本文的源码托管地址:https://github.com/lampo1024/TsBlog/releases/tag/v1.5

本文学习到此结束,本系列未完待续,我们下期再见……

如果你喜欢Rector的本系列文章,请为我点个大大的赞,以支持Rector在后续的写作中更有基(激)情,哈哈。。。

本文同步发表至 图享网一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](五)

一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](五)的更多相关文章

  1. 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](六)

    前言 大家好,我是Rector 又是星期五,很兴奋,很高兴,很high...啦啦啦... Rector在图享网又和大家见面啦!!!上一篇<一步一步创建ASP.NET MVC5程序[Reposit ...

  2. 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](一)

    前言 大家好,我是Rector 从今天开始,Rector将为大家推出一个关于创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar]的文章系列, ...

  3. 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](四)

    前言 上一篇<一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](三)>,我们完成了: * 引用SqlSugar * ...

  4. 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](三)

    前言 上一篇<一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](二)>我们通过如下操作: 创建实体及工具类 创建Re ...

  5. 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](二)

    前言: 在本系列第一篇<一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](一)>中,我为大家介绍了搭建空白解决方案以 ...

  6. 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](七)

    前言 大家好,我依旧是你们的老朋友Rector,很高兴又在周五的时候准时和大家见面. Rector的系列文章[一步一步创建ASP.NET MVC5程序[Repository+Autofac+Autom ...

  7. 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](八)

    前言 Hi, 大家好,还是星期五,还是Rector,又在图享网准时和大家见面了. 今天给大家带来系列教程<一步一步创建ASP.NET MVC5程序[Repository+Autofac+Auto ...

  8. 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](九)

    前言 童鞋们,大家好 我是专注.NET开发者社区建设的实践者Rector. 首先,为自己间隔了两个星期五再更新本系列文章找个不充分的理由:Rector最近工作,家庭的各种事务所致,希望大家谅解. 本文 ...

  9. 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](十)

    前言 朋友们, 大家好,我还是Rector,写ASP.NET MVC 5系列文章[一步一步创建ASP.NET MVC5程序Repository+Autofac+Automapper+SqlSugar] ...

随机推荐

  1. 「mysql优化专题」90%程序员没听过的存储过程和存储函数教学(7)

    一.MYSQL储存过程简介(技术文): 储存过程是一个可编程的函数,它在数据库中创建并保存.它可以有SQL语句和一些特殊的控制结构组成.当希望在不同的应用程序或平台上执行相同的函数,或者封装特定功能时 ...

  2. MVC+EF 入门教程(三)

    一.前言 上一节,我们将了生成数据库,那么这张我就将操作设计库. 二.在 Aplication 定义服务 在 Application 中添加文件夹(Blog)和 操作类(BlogServer).实例如 ...

  3. go实例之函数

    1.可变参数 示例代码如下: package main import "fmt" // Here's a function that will take an arbitrary ...

  4. C#中Abstract和Virtual[转载]

    原文:http://www.cnblogs.com/blsong/archive/2010/08/12/1798064.html 在C#的学习中,容易混淆virtual方法和abstract方法的使用 ...

  5. Java集合(一) CopyOnWriteArrayList

    CopyOnWriteArrayList 类分析   1. CopyOnWriteArrayList 其中底层实现存放数据是一个Object数组:   private volatile transie ...

  6. Java编程学习知识点分享 入门必看

    Java编程学习知识点分享 入门必看 阿尔法颜色组成(alpha color component):颜色组成用来描述颜色的透明度或不透明度.阿尔法组成越高,颜色越不透明. API:应用编程接口.针对软 ...

  7. 点击盒子选中里面的单选框,并给盒子添加相应样式,美化单选框、复选框样式css用法,响应式滴

    pc效果图: 移动端效果图: 代码直接上: <!DOCTYPE html> <html> <head> <meta http-equiv="Cont ...

  8. 手动编译protobuf3的C++源码

    Windows下编译 官方文档 第三方文档 准备工具 Visual Studio 2013 CMake https://cmake.org/ Git https://git-scm.com/ 需要注意 ...

  9. linux 操作中命令备忘

    1 使用grep 查询关键内容 如果你想在当前目录下 查找"hello,world!"字符串,可以这样: grep -rn "hello,world!" * * ...

  10. 解决adb push时出现的"Read-only file system"问题

    欢迎和大家交流技术相关问题: 邮箱: jiangxinnju@163.com 博客园地址: http://www.cnblogs.com/jiangxinnju GitHub地址: https://g ...