如何与标量值结合

时间:2017-10-19 06:02:57

标签: entity-framework

在这个伪代码中,最后一行不会起作用,因为标量值不是IQueryable。

var scalarValue = 7;

var qry = (from t in db.Table
           where t.Filter == 5 //Arbitrary
           select t.ID);

var unioned = qry.Union(scalarValue);

在SQL中很简单:

select t.ID
from Table

union

select 7;

在我的场景中,我确实需要选择有效的Table.ID,因此解决方法是:

var scalarValue = 7;

var qry = (from t in db.Table
           where t.Filter == 5 //Arbitrary
           select t.ID);

var scalarQry = (from t in db.Table
           where t.ID == scalarValue
           select t.ID);           

var unioned = qry.Union(scalarQry);

但是,如果有办法输出"选择7;"例如,那就是我对这个问题的看法。

1 个答案:

答案 0 :(得分:1)

写作

MyContext.MyClass.Select(t => t.Id).Union(new List<long>() { 42 }).ToList();

生成以下SQL查询(MyClassDbSet<MyClass>):

SELECT 
    [Distinct1].[C1] AS [C1]
    FROM ( SELECT DISTINCT 
        [UnionAll1].[MyClassId] AS [C1]
        FROM  (SELECT 
            [Extent1].[MyClassId] AS [MyClassId]
            FROM [dbo].[MyClasss] AS [Extent1]
        UNION ALL
            SELECT 
            cast(42 as bigint) AS [C1]
            FROM  ( SELECT 1 AS X ) AS [SingleRowTable1]) AS [UnionAll1]
    )  AS [Distinct1]

被调用的Union的重载是:

public static IQueryable<TSource> Union<TSource>(this IQueryable<TSource> source1, IEnumerable<TSource> source2) 
System.Linq.Queryable中的

我希望这符合您的需求