AutoMapper for combining records from 2 tables into a single IEnumerable viewmodel

I have 2 tables, say T1and T2. T1contains oID, cID, date, status and T2contains cID, cName, cURL . I developed a class for 2 tables 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;}

}

cIDin T1there foreign key, referring toT2 - cID

Now I have a view model T3as shown below to combine T1andT2

T3.cs

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

T3 extends T1 T2 T3. , 2 AutoMapper. , T1 T2, 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 . , 2- cID. , ?

+4
2

, - :

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;
});
+2

cID, T1:

public class T3:T1
{
   public int cID{get;set;}  //need to remove
   public string cName{get;set;}
   public string cURL{get;set;}
}

T1-T3:

   Mapper.CreateMap<T1, T3>()
    .ForMember(dest => dest.cName, opt => opt.Ignore())
    .ForMember(dest => dest.cURL, opt => opt.Ignore());

T2-T3:

  Mapper.CreateMap<T2>, T3>()
   .ForMember(dest => dest.oID, opt => opt.Ignore())
   .ForMember(dest => dest.date, opt => opt.Ignore())
   .ForMember(dest => dest.status, opt => opt.Ignore());
+1

Source: https://habr.com/ru/post/1665158/


All Articles