在公司里,学到了很多知识,其中就包括AutoMapper。为什么要用AutoMapper呢?不知道大家有没有在做添加操作的时候一行行写代码添加数据很麻烦,AutoMapper就很轻松的解决了此类问题。下面为大家讲解AutoMapper的用法:
在项目中:工具>NuGet包管理器>管理解决方案的NuGet程序包。搜索AutoMapper下载AutoMapper.
然后引用
using AutoMapper;
这个时候我们就可以使用AutoMapper来做增删改操作了。
修改操作:
Mapper.Instance.Map(accountInputModel, accountEntity);
accountInputModel为传入的参数类。当然也会跟实体类的字段相对应。
accountEntity为根据当前需要修改的ID查出的一列数据。
这样就可以完成修改操作了,减去了一行行赋值的过程。
添加操作:
AutoMapper.Mapper.Map<AccountEntity>(accountInputModel);
accountInputModel跟上面的同理,都是输出类,但是会跟数据库相对应。
如
[AutoMap(typeof(AccountEntity))]
public class AccountInputModel
{
public int Id { get; set; }
public string AccountName { get; set; }
public string Password { get; set; }
public int Classify { get; set; }
public DateTime RegisterTimes { get; set; }
}
数据库中有ID、AccountName 、Password、Classify 、RegisterTimes 字段
其他的操作我就不一一说明了。都类似。
注:哪个项目中需要用到AutoMapper就在哪个项目中安装。
AccountEntity为实体类,跟数据库字段一一对应。可参考实体类映射数据库那篇文章。