C# 实现对象映射Mapster

时间:2020-07-21 22:01:58   收藏:0   阅读:193

下面是简单例子

1引用Mapster.dll包

2.初始化,设置映射规则

class ModelA{
  public string UserId{get;set;}
  public string Remark{get;set;}
}

class ModelB{
  public string User_id{get;set;}
  public string Remark_msg{get;set;}
  public int Lab_id{get;set;}
}


public static void InitMapster() // 初始化(设置映射规则) {
        // modelA 映射到 modelB TypeAdapterConfig<ModelA, ModelB> .NewConfig() .AddDestinationTransform((string x) => !string.IsNullOrWhiteSpace(x) ? x : " ") // 空值替换 .Map(dest => dest.Lab_id, src => MapContext.Current.Parameters["labId"]) // 传递运行时值 .Map(dest => dest.User_id, src => src.UserId) .Map(dest => dest.Remark_msg, src => src.Remark); }

3.使用映射

// 调用Mapster 将  List<ModelA> modelAs 映射到 List<ModelB> modelBs
public void test()
  {
    List<modelA> modelAs = ...;
  int labId = 1; var modelBs = modelAs.BuildAdapter() .AddParameters("labId", labId) // 设置值 .AdaptToType<List<ModelB>>(); // 将某一实体映射成List<ModelB>
  }

  

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!