关于项目中使用AutoMapper的问题

在公司里,学到了很多知识,其中就包括AutoMapper。为什么要用AutoMapper呢?不知道大家有没有在做添加操作的时候一行行写代码添加数据很麻烦,AutoMapper就很轻松的解决了此类问题。下面为大家讲解AutoMapper的用法:

在项目中:工具>NuGet包管理器>管理解决方案的NuGet程序包。搜索AutoMapper下载Au­toMap­per.

然后引用

using AutoMap­per;

这个时候我们就可以使用Au­toMap­per来做增删改操作了。

修改操作:

Mapper.Instance.Map(accountInputModel, accoun­tEn­ti­ty);

accountInputModel为传入的参数类。当然也会跟实体类的字段相对应。

accoun­tEn­ti­ty为根据当前需要修改的ID查出的一列数据。

这样就可以完成修改操作了,减去了一行行赋值的过程。

添加操作:

AutoMapper.Mapper.Map<AccountEntity>(accountInputModel);

accountInputModel跟上面的同理,都是输出类,但是会跟数据库相对应。

[AutoMap(typeof(AccountEntity))]
pub­lic class AccountInputModel
{
pub­lic int Id { get; set; }
pub­lic string Account­Name { get; set; }
pub­lic string Pass­word { get; set; }
pub­lic int Clas­si­fy { get; set; }

pub­lic Date­Time Reg­is­ter­Times { get; set; }

}

数据库中有ID、AccountName 、Password、Classify 、Reg­is­ter­Times 字段

其他的操作我就不一一说明了。都类似。

注:哪个项目中需要用到AutoMapper就在哪个项目中安装。

AccountEntity为实体类,跟数据库字段一一对应。可参考实体类映射数据库那篇文章。

 

为您推荐

发表评论

您的电子邮箱地址不会被公开。