将匿名类型转换为IEnumerable<>在EF6中 [英] Convert Anonymous type to IEnumerable<> in EF6

查看:58
本文介绍了将匿名类型转换为IEnumerable<>在EF6中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Entity Framework开发MVC应用程序.我想从表中获取5列,并以 IEnumerable 类型返回它们.我的代码是:

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:

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

但这给了我错误

无法隐式转换类型 'System.Collection.Generic.List <Anonymous#1>'至 'System.Collection.Generic.IEnumerable <<MST>>'

Cannot implicitly convert type 'System.Collection.Generic.List<Anonymous#1>' to 'System.Collection.Generic.IEnumerable<<MST>>'

我该如何解决?

推荐答案

首先,您不需要ToList(),因为您不需要列表:

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)

现在,您需要将类型设置为MST.如果这是EF知道的类型,则可以将其直接包含在Select:

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)

但不是,因此您需要使用AsEnumerable从EF切换到内存,然后在此之后创建MST:

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

((如果出于某些原因您确实确实需要ToList(),则可以使用它代替AsEnumerable(),但是最好在所有这些之后放置最后一个ToList()以得到列表)真正想要的类型.

(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<MST> 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 });

这篇关于将匿名类型转换为IEnumerable&lt;&gt;在EF6中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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