C#no强制运算符是在类型匿名对象之间定义的

问题描述 投票:0回答:1

我目前正在ASP.NET 4.5应用程序中进行LINQ查询。我尝试从不同的角度查询2个列表,合并结果并返回第一个表的数据类型的IQueryable。

我的数据库中的表有类似的字段,所以我可以选择我需要的匿名对象。

我的查询如下所示:

var coolStuff = ctx.CoolStuffTable.Select(x => new
{
    PK = x.PK,
    CreationDate = x.CreationDate,
    ModificationDate = x.ModificationDate,
    Titel = x.Title,
    Visible = x.Visible
});

var niceStuff = ctx.NiceStuffTable.Select(x => new
{
    PK = x.PK,
    CreationDate = x.CreationDate,
    ModificationDate = x.ModificationDate,
    Title = x.Title,
    Visible = x.Visible
});

var result = coolStuff.Union(nicelStuff)
        .Where(i => i.Visible);

var result = result.Cast<CoolStuffTable>(); // the LinqToSQL class of thable CoolStuffTable is also called CoolStuffTable

它看起来实际上相当不错,但是我得到了这个

类型之间没有定义强制运算符

当然,我可以在SQL server中编写一个视图,但我想在LINQ中解决这个问题...

你知道如何查询2个不同的表,联合它们并返回类型表1(CoolStuffTable)吗?

谢谢!!!

c# asp.net linq
1个回答
2
投票

你需要再次投射到CoolStuffTable

var result = coolStuff.Union(nicelStuff)
                      .Where(i => i.Visible)
                      .Select(s => new CoolStuffTable
                        {
                               PK = s.PK,
                               CreationDate = s.CreationDate,
                               ModificationDate = s.ModificationDate,
                               Title = s.Title,
                               Visible = s.Visible
                        });
© www.soinside.com 2019 - 2024. All rights reserved.