通过EF / Linq的伸入KeyValuePair [英] Projecting into KeyValuePair via EF / Linq

查看:91
本文介绍了通过EF / Linq的伸入KeyValuePair的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从EF / Linq查询这样的加载KeyValuePairs的列表:

I'm trying to load a list of KeyValuePairs from an EF / Linq query like this:

return (from o in context.myTable 
select new KeyValuePair<int, string>(o.columnA, o.columnB)).ToList();



我的问题是,这导致错误只有无参数的构造函数和初始化在LINQ是支持实体。

My problem is that this results in the error "Only parameterless constructors and initializers are supported in LINQ to Entities."

有没有解决这个简单的方法?我知道我可以创建一个自定义类本,而不是使用KeyValuePair但这似乎是重新发明轮子。

Is there an easy way around this? I know I could create a custom class for this instead of using KeyValuePair but that does seem like re-inventing the wheel.

推荐答案

从表中选择只columnA和columnB,并在内存中移动进一步的处理:

Select only columnA and columnB from your table, and move further processing in memory:

return context.myTable
              .Select(o => new { o.columnA, o.columnB }) // only two fields
              .AsEnumerable() // to clients memory
              .Select(o => new KeyValuePair<int, string>(o.columnA, o.columnB))
              .ToList();



考虑也创造字典包含KeyValuePairs:

Consider also to create dictionary which contains KeyValuePairs:

return context.myTable.ToDictionary(o => o.columnA, o => o.columnB).ToList();

这篇关于通过EF / Linq的伸入KeyValuePair的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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