Convert Anonymous type to IEnumerable<> in EF6

后端 未结 2 1851
轮回少年
轮回少年 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:16

    First you don't need the ToList() because you don't need a list:

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

    Now you do need the type to be MST. If this was a type EF knew about you could include this directly in the Select:

    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)
    

    But it's not, so you need to break from EF to in-memory with AsEnumerable and then do the creation of MST after that:

    IEnumerable 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 });
    

    (If there's some reason why you really do need the ToList() you can use that instead of AsEnumerable(), but you're probably better off just placing a final ToList() after all of that, to get a list of the type you actually want).

    If you were using asynchronous code, then we would similarly place it after the await:

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

提交回复
热议问题