AutoMap - 使用心得

  • 2329
  • 0

此篇簡單介紹 AutoMap 第三方套件,AutoMap 在轉換物件型別的資料特別好用!!


 

Entity 的 Model 如下: 

        public partial class Post
        {
            public int Id { get; set; }
            public string Title { get; set; }
            public string PostContent { get; set; }
            public System.DateTime CreateDateTime { get; set; }
            public Nullable<System.DateTime> LastModifyDateTime { get; set; }
        }

View 的 ViewModel 如下 :

        public class IndexViewModel
        {
            public int Id { get; set; }
            public string Title { get; set; }
            public string PostContent { get; set; }
        }

 

使用操作與差異 : (使用 EF 取得資料)

在沒有使用 AutoMap 的情況下

        public List<IndexViewModel> Index()
        {
            // 在沒有AutoMap的輔助的Code
            List<IndexViewModel> viewModel = new List<IndexViewModel>();
            foreach (var item in db.Post.ToList())
            {
                viewModel.Add(new IndexViewModel() {
                    Id = item.Id,
                    PostContent = item.PostContent,
                    Title = item.Title
                });
            }

            return viewModel;
        }

在使用 AutoMap 的情況下 : 

        public List<IndexViewModel> Index()
        {
            // 定義Post是來源的Class而IndexViewModel是最後結果
            Mapper.CreateMap<Post, IndexViewModel>();
            // 把List<Post>轉成List<IndexViewModel>
            var viewModel2 = Mapper.Map<List<IndexViewModel>>(db.Post.ToList());
            // 另一種方式 AutoMapper QuerableExtension
            var viewModel3 = (db.Post.Project().To<IndexViewModel>()).ToList();

            return viewModel2; // or viewModel3
        }

 

AutoMap 已知有兩種模式產生資料

第一種 修改資料模型 : 
假設 現況有 Model && ViewModel 這兩個 模型對應
var cfg = new MapperConfigurationExpression(); // 建立設定
cfg.CreateMap<ViewModel1, Model1>(); // 對應 <來源,欲修改> 
Mapper.Initialize(cfg);
Mapper.Map(ViewModel, Model); // 此時 AutoMap 將使用 ViewModel 修改 Model 的資料
第二種 不修改模型資料的,產生出新的模型物件 :
假設 現況有 Model && ViewModel 這兩個 模型對應
var cfg = new MapperConfigurationExpression(); // 建立設定
cfg.CreateMap<ViewModel1, Model1>(); / /對應 <來源,欲修改> 
Mapper.Initialize(cfg);
var converted = Mapper.Map<Model>(ViewModel); // 依據 ViewModel的資料 建立出 <Model>型別的物件

 

自定義 AutoMap 的方法 : 

    static TViewModel_2 ConvertModelToModel<TSource_1, TViewModel_2>(TSource_1 list)
    {
        // 初始化設定
        Mapper.Initialize(cfg =>
        {
            cfg.CreateMissingTypeMaps = true;
            cfg.CreateMap<TSource_1, TViewModel_2>().ReverseMap(); //可反轉 
        });
        Mapper.Configuration.AssertConfigurationIsValid();
     
        // 把資料帶入
        var converted = Mapper.Map<TViewModel_2>(list);
        return converted;
    }

 

 


多多指教!! 歡迎交流!!

你不知道自己不知道,那你會以為你知道