Convert Anonymous type to IEnumerable<> in EF6

后端 未结 2 1855
轮回少年
轮回少年 2021-01-23 08:30

I am developing an MVC application using Entity Framework. I want to get 5 columns from a table and return them in an IEnumerable type. My code for this is:

2条回答
  •  耶瑟儿~
    2021-01-23 09:19

    You need to simply project the Type MST instead of anonymous type:-

    n = db.MSTs.Select(x => new MST 
                          { 
                              Id = x.Id, 
                              Code = x.Code,
                              Desc =  x.Desc, 
                              L1= x.L1, 
                              L2 = x.L2 
                           }).OrderBy(h => h.Code);
    

    Provided, you have all these properties in MST. Also, it should not be a mapped entity it should be a DTO.

    Also, you don't need ToList here since Select returns IEnumerable.

    Update:

    Since it is a mapped entity in Entity Framework, one way is to first project the anonymous type and then the Model type like this:-

    n = db.MSTs.Select(x => new 
                              { 
                                  x.Id, 
                                  x.Code,
                                  x.Desc, 
                                  x.L1, 
                                  x.L2 
                               }).OrderBy(h => h.Code)
                               .AsEnumerable()
                               Select(x => new MST 
                                       { 
                                          Id = x.Id, 
                                          Code = x.Code,
                                          Desc =  x.Desc, 
                                          L1= x.L1, 
                                          L2 = x.L2 
                                       });
    

提交回复
热议问题