AutoMapper将2个表中的记录联接到单个IEnumerable视图模型中 [英] AutoMapper to join records from 2 tables into single IEnumerable viewmodel

查看:58
本文介绍了AutoMapper将2个表中的记录联接到单个IEnumerable视图模型中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个表,例如 T1 T2 . T1 包含 oID,cID,日期,状态,而 T2 包含 cID,cName,cURL .我为上面的2个表设计了类,如下所示:

I have 2 Tables, say T1 and T2. T1 contains oID,cID,date,status and T2 contains cID,cName,cURL. I have designed class for above 2 tables as below:

T1.cs

public class T1{
  public int oID{get;set;}
  public int cID{get;set;}
  public DateTime date{get;set;}
  public string status{get;set;}
}

T2.cs

public class T2{
    public int cID{get;set;}
    public string cName{get;set;}
    public string cURL{get;set;}

}

T1 中的

cID 是引用 T2-cID

现在,我有如下的 T3 视图模型,用于结合 T1 T2

Now I have my T3 view model as below to combine T1 and T2

T3.cs

public class T3:T1
{
   public int cID{get;set;}
   public string cName{get;set;}
   public string cURL{get;set;}
}

T3 扩展了 T1 T2 属性是在 T3 中定义的.因此,我打算使用 AutoMapper 在一个视图模型中合并2个表.我有以下方法从 T1 获取所有详细信息,并从 T2 获取相关详细信息,填充后将返回 IEnumerable T3 .

T3 extends T1 and T2 properties are defined in T3. Thus I was intending to combine 2 tables in a single view model using AutoMapper. I have below method to get all details from T1 and related details from T2, which when filled will return IEnumerable T3.

public IEnumerable<T3> GetAll()
{
   var od = mycontext.t1repository.GetMany().ToList();
   var ck = myContext.t2repository.GetMany(x => od.All(y => y.cID == x.cID)).ToList();
   if (od.Any())
   {
        Mapper.CreateMap<tblT1, T3>();
        Mapper.CreateMap<tblT2, T3>()
                    .ForMember(x=>x.cID, a => a.MapFrom(s => s.cID))
        var response = Mapper.Map<List<T1>, List<T3>>(od);
        return response;
   }
   return null;
}

我通过 此答案 尝试了上述代码但这是针对单个实例的,我必须返回记录的 IEnumerable .我不确定如何根据其 cID 实际映射2表中的数据.知道我该如何实现吗?

I tried the above code via this answer but that is for single instance and I have to return IEnumerable of records. I am not sure how I can actually map data's from 2 table based on their cID. Any idea how I can achieve this?

推荐答案

我认为您可以尝试执行以下操作:

I think you can try something like this:

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<T1, T3>();
    cfg.CreateMap<T2, T3>();
});

var mapper = config.CreateMapper();

var od = new List<T1> { ... };
var ck = new List<T2> { ... };

var result = od.Join(ck, t => t.cID, t => t.cID, (t1, t2) =>
{
    var t3 = mapper.Map<T1, T3>(t1);
    t3 = mapper.Map<T2, T3>(t2, t3);

    return t3;
});

这篇关于AutoMapper将2个表中的记录联接到单个IEnumerable视图模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆