首页 新闻 会员 周边

.net core 升级到6以后使用Union查询的问题

0
[已解决问题] 解决于 2022-07-12 10:13

var qry = (
from item in _context.Table1
select new SomeModel
{
Name = "A"
}
)
.Union
(
from item in _context.Table2
select new SomeModel
{
Name = item.UserName
}
).ToList();

查询抛出异常:Unable to translate set operation when matching columns on both sides have different store types.

这是什么原因?UserName也是string类型,为什么无法转换?2.1版本并不会出现这样的问题。

四夕木的主页 四夕木 | 菜鸟二级 | 园豆:204
提问于:2022-07-04 20:20
< >
分享
最佳答案
0

算是一个已知的bug:https://github.com/dotnet/efcore/issues/24707

解决办法:Name = item.UserName.ToString()

奖励园豆:5
talentzemin | 小虾三级 |园豆:759 | 2022-07-04 22:49

不允许先做强制转换:
:“Unable to translate set operation after client projection has been applied. Consider moving the set operation before the last 'Select' call.”

四夕木 | 园豆:204 (菜鸟二级) | 2022-07-05 10:34
其他回答(3)
0

暂无解决方案,看来只有换另外的处理方式,等待官方解决。

四夕木 | 园豆:204 (菜鸟二级) | 2022-07-12 10:12
0

var resultA=(from item in _context.Table1
select new SomeModel
{
Name = "A"
}).ToList();
var resultB=(from item in _context.Table2
select new SomeModel
{
Name = item.UserName
}).ToList();
var qry=resultA.AsEnumerable().Union(resultB).ToList();

https://learn.microsoft.com/en-us/answers/questions/913202/unable-to-translate-set-operation-when-matching-co.html

Tiye529 | 园豆:204 (菜鸟二级) | 2022-11-12 14:42
0

这个问题的原因是在 Union 之前,不应该使用无法被 EFCore 翻译为 数据库查询的类(例如 SomeModel)
进行如下修改:

var qry = (
from item in _context.Table1
select new
{
Id = item.id
Name = "A"
}
)
.Union
(
from item in _context.Table2
select new
{
Id = item.id
Name = item.UserName
}
).
Select(x=> new SomeModel { Name = x.Name })
ToList();

hesi | 园豆:202 (菜鸟二级) | 2023-09-13 11:31

类似如如下代码:

支持(0) 反对(0) hesi | 园豆:202 (菜鸟二级) | 2023-09-13 11:34

同一个 audit 表,根据 audit_type 的不同去关联不同表进行查询(并对不同表进行不同的关键字搜索),然后进行 union all 操作,

按照 create_time 排序,
最后才进行转换;

支持(0) 反对(0) hesi | 园豆:202 (菜鸟二级) | 2023-09-13 11:36
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册