Linq to Entity 连接(join) Linq to Object
数据库的数据代码Linq to Entity在join前,内存中数据代码Linq to Object在join后。代码如下:
- var entityNames = (from en in entitySet
- join ob in objectList
- on en.SID equals ob.Identity
- select en.Name).ToList();
好了,编译通过,运行时抛异常了。
Only Primitive types ('Such as Int32, string, and Guid') are supported in this context
中文意思是“无法创建类型为“项目名.MyObject”的常量值。此上下文仅支持基元类型(“例如 Int32、String 和 Guid”)"
看来在涉及这种操作时,我们内存中的数据还不能是非基元类型。List<MyObject> objectList = new List<MyObject>();
MyObject要为int32, string或者Guid,才能运行通过,并且不是整表查询,而是针对name列的单独查询。大家可以一试。
所以在这里给出大家一点建议:
在涉及到内存中的对象与EF里的对象混合查询时,如果内存中的对象不为基元类型,则先把其中的某个要参加匹配的变量查询出来,再拿着它与EF对象混合查询。
这样不仅不会出错,效率也高,且代码会两段写,也容易看清楚意思。
以上的代码这样,才是最佳的
- IEnumerable<long> idList = objectList.Select(o => o.Identity);
- var entityNames = (from en in entitySet
- join id in idList
- on en.SID equals id
- select en.Name).ToList();
数据库查询语句如下:
- SELECT
- [Extent1].[Name] AS [Name]
- FROM [dbo].[Entity] AS [Extent1]
- INNER JOIN (SELECT
- [UnionAll1].[C1] AS [C1]
- FROM (SELECT
- cast(1 as bigint) AS [C1]
- FROM ( SELECT 1 AS X ) AS [SingleRowTable1]
- UNION ALL
- SELECT
- cast(2 as bigint) AS [C1]
- FROM ( SELECT 1 AS X ) AS [SingleRowTable2]) AS [UnionAll1]
- UNION ALL
- SELECT
- cast(3 as bigint) AS [C1]
- FROM ( SELECT 1 AS X ) AS [SingleRowTable3]) AS [UnionAll2] ON CAST( [Extent1].[SID] AS bigint) = [UnionAll2].[C1]
虽然里面的操作是麻烦了点,但是最后查询出来的东西却只有Name一个。相对而言,还是比较好的。
============ 欢迎各位老板打赏~ ===========
与本文相关的文章
- · Linq to entity多表查询如何返回查询结果
- · The instance of entity type ‘Customer’ cannot be tracked because another instance with the same key value for {‘Id’} is already being tracked.
- · .NET8实时更新nginx ip地址归属地
- · 解决.NET Blazor子组件不刷新问题
- · .NET8如何在普通类库中引用 Microsoft.AspNetCore
- · .NET8 Mysql SSL error
- · ASP.NET Core MVC的Razor视图渲染中文乱码的问题
- · .NETCORE 依赖注入服务生命周期
- · asp.net zero改mysql
- · .NET5面试汇总
- · .Net连接Mysql数据库的Convert Zero Datetime日期问题
- · vue使用element-ui中的Message 、MessageBox 、Notification
😆