gpt4 book ai didi

c# - Linq to Entities 中的 Union 错误

转载 作者:可可西里 更新时间:2023-11-01 08:23:21 30 4
gpt4 key购买 nike

我在要合并 2 个列表的查询中遇到问题。

我想将表 PlacesLocations 中的记录合并到 View 模型属性 Places 中。

Fruits = (from e in db.Fruits
where !e.Excluded
select new FruitViewModel()
{
CodFood = e.CodFood,
Name = e.Name,
Color = e.Color,
Places = (from p in e.Places
where !p.Excluded
select new FruitViewModel()
{
CodPlace = p.CodPlace,
Name = p.Name
}).Union(
from r in e.Locations
where !r.Excluido
select new FruitViewModel()
{
CodLocation = r.CodLocation,
Name = p.Name
})
}),

但它给了我:

System.NotSupportedException: The type 'Project.ViewModel.Fruits.FruitsViewModel' appears in two structurally incompatible initializations within a single LINQ to Entities query. A type can be initialized in two places in the same query, but only if the same properties are set in both places and those properties are set in the same order.

我可以在 Linq 执行后合并为 this answer ,但我想保持简单,不要过多更改此代码,如果可能的话 - 在延迟执行之前进行查询。

我该如何解决?

最佳答案

根据错误消息,您的 FruitViewModel 初始化似乎有问题。试试这个:

           Places = (from p in e.Places
where !p.Excluded
select new FruitViewModel()
{
CodLocation = "",
CodPlace = p.CodPlace,
Name = p.Name
}).Union(
from r in e.Locations
where !r.Excluido
select new FruitViewModel()
{
CodLocation = r.CodLocation,
CodPlace = "",
Name = p.Name
})

关于c# - Linq to Entities 中的 Union 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22231778/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com