1. 程式人生 > >Asp.Net AutoMapper用法

Asp.Net AutoMapper用法

初始化 omap model2 sys ron ria space 創建 sna

1、AutoMapper簡介

用於兩個對象映射,例如把Model的屬性值賦值給View Model。傳統寫法會一個一個屬性的映射很麻煩,使用AutoMapper兩句代碼搞定。

2、AutoMapper安裝

推薦使用nuget搜索AutoMapper安裝

3、AutoMapper簡單用法

先建個model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace cms.Web.Models
{public class book
    {
        
public int ID { get; set; } public string name { get; set; } public string className { get; set; } } public class bookViewModel { public int ID { get; set; } public string name { get; set; } public string className { get; set; }
public int price { get; set; } public string des { get; set; } } }

controller代碼

public object ceshi()
        {
            book data = new book { ID = 1, name = "少年1號", className = "娛樂" };

            //映射初始化寫法1
            Mapper.Initialize(x => x.CreateMap<book, bookViewModel>());

            
////映射初始化寫法2 //Mapper.Initialize(config => //{ // config.CreateMap<book, bookViewModel>(); //}); ////映射初始化寫法3 //var cfg = new MapperConfigurationExpression(); //cfg.CreateMap<book, bookViewModel>(); //cfg.CreateMap<bookViewModel, book>(); //Mapper.Initialize(cfg); //映射-寫法1:由AutoMapper創建目標對象 var vmodel = Mapper.Map<book, bookViewModel>(data); //映射 - 寫法2:讓AutoMapper把源對象中的屬性值合並 / 覆蓋到目標對象(推薦 bookViewModel vmodel2 = new bookViewModel(); Mapper.Map(data, vmodel2); //return vmodel.ToString(); return JsonConvert.DeserializeObject(JsonConvert.SerializeObject(vmodel2)); }

4、AutoMapper高級用法

https://www.cnblogs.com/youring2/p/automapper.html

http://www.cnblogs.com/1-2-3/p/AutoMapper-Best-Practice.html

Asp.Net AutoMapper用法