您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息

C#中关于AutoMapper应用的实例

2024/4/19 15:13:05发布6次查看
最近发现了一个比较有趣的东西 automapper,主要将model转换为dto,dto更注重数据,对领域对象进行合理封装,从而不会将领域对象的行为过分暴露给表现层。
先来看一点实例,两个类之前的映射。
首先定义两个类source与dtosource:
public class source { public int id { get; set; } public string content { get; set; } } public class dtosource { public int id { get; set; } public string content { get; set; } }
source与dtosource字段完全相同,来看看它俩如何通过automapper转换,代码很简单。
mapper.initialize(x=>{ x.createmap<source,dtosource>(); }); source s = new source{id=1,content="123"}; dtosource dto = mapper.map<dtosource>(s);
第一步建立source到dtosource之间的映射,初始化一个source实例后,来看下执行结果:
执行完成后,可以看到dto中的数据与之前初始化的s的数据是一样的,就像是直接将s拷贝了一份给dto,在两个类字段名定全相同的情况下如此,那么如果dtosource中的字段名与source中的不相同如何,其实也很简单,只需
要改成一点点的代码既可:
我们将dtosource中的content的字段名改成desc,此时只需要建立映射关系时,指定字段就可以了:
1 mapper.initialize(x => { 2 x.createmap<source, dtosource>().formember(c=>c.desc,q=> { 3 q.mapfrom(z => z.content); 4 }); 5 });
来看看运行结果如何;
可以看到与之前的运行结果是相同的。
那么如何映射两个list,其实也很简单,和上述代码几乎可以说是无差别,只是在最后一步时,要做一点点的修改就可以了。如下面代码:
mapper.initialize(x => { x.createmap<source, dtosource>().formember(c => c.desc, q => { q.mapfrom(z => z.content); }); }); s.add(new source { id = 1, content = "123" }); var dto = mapper.map<list<dtosource>>(s);
可以看到除了最后一句代码,其它几乎是完全相同的,只是在最后一句代码中,目标类型改成了list<dtosource>仅此而已。看下运行结果如何:
结果符合预期。
在实际的项目中,这样的写法肯定是不符合要求的,一般会做一个封装,新建一个sourceprofile继承自profile:
1 public sourceprofile() 2 { 3 base.createmap<source, dtosource>().formember(c => c.desc, q => { 4 q.mapfrom(z => z.content); 5 }); 6 }
所有映射关系都可以写在这一个类里,只需要在程序初始化的时候调用一次就可以了:
1 mapper.initialize(x =>{ x.addprofile<sourceprofile>(); });
博主使用的automapper版本6.1.1.0,因为automapper在6.0版本时移除了profile中的configure,所以与6.0版本以下写法有点不同,6.0以下版本写法为:
public class sourceprofile : profile { protected override void configure() { createmap<source, dtosource>().formember(c => c.desc, q => { q.mapfrom(z => z.content); }); } }
继承profile重写其configure即可,调用方式与上述没有太大差别。 mapper.initialize中可添加一个或多个profile。
在mvc项目的应用中,可以将mapper.initialize封装到一个类里;
public static class automapperformvc { public static void register() { mapper.initialize(x => { x.addprofile<sourceprofile>(); }); } }
进而在mvc的global中进一次性注册:
public class mvcapplication : system.web.httpapplication { protected void application_start() { arearegistration.registerallareas(); filterconfig.registerglobalfilters(globalfilters.filters); routeconfig.registerroutes(routetable.routes); bundleconfig.registerbundles(bundletable.bundles); //注册 automapperformvc.register(); } }
以上就是c#中关于automapper应用的实例的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录