c# - 具有未知数据类型的 LINQ 的 .Union()

标签 c# sql-server linq

我需要从不同的数据库获取数据,然后将这两个数据集组合成一个 IQueryable 集合。

数据库 #1 数据示例:

-- SOLUTION #1
[ID] [int],
[Name] [nvachar](50),
[ExpirationDate] [datetime],
[Users] [int]

数据库 #2 数据示例:

-- SOLUTOIN #1
[ID] [int],
[Name] [nvarchar](50),
[Users] [int]

如您所见,数据库 #2 中的解决方案没有 ExpirationDate 属性,这在执行 Union() 时给我带来了一些问题。


我尝试了以下方法:

public static IQueryable GetAll()
{
    var list = (from solution1 in db1.Solutions
            select new
            {
                Id = solution1.ID,
                Name = solution1.Name,
                ExpirationDate = solution1.ExpirationDate,
                Users = solution1.Users
            })
        .Union(from solution2 in db2.Solutions
            select new{
                Id = solution2.ID,
                Name = solution2.Name,
                ExpirationDate = (DateTime?) null,
                Users = solution2.Users        
            });
}

但不幸的是,这不起作用。调用它时,出现以下异常:

Object reference not set to an instance of an object.

我想这是因为我设置了 ExpirationDate = (DateTime?) null


我也试过从 SQL View 中获取数据,就像这样(这是 db2 的一个示例,因为 db1 有点不言自明)

CREATE VIEW [dbo].[v_Solutions]
    AS SELECT s.ID,
        s.Name,
        null AS [ExpirationDate],
        s.Users
    FROM Solution

然后将 LINQ select new 语句更改为以下内容:

.Union(from solution2 in db2.Solutions
            select new{
                Id = solution2.ID,
                Name = solution2.Name,
                ExpirationDate = (DateTime?) solution2.ExpirationDate,
                Users = solution2.Users        
            });

但是这样做会给我一个编译错误:

Cannot convert type 'int?' to 'System.DateTime?'

尽管 solution2.ExpirationDate 中的数据应该只是 null

我不太确定如何完成此声明。有什么想法吗?

最佳答案

LINQ 2 SQL 和 EF 不支持从多个数据库上下文中提取的查询。显然,您甚至触发了一个导致 NullReferenceException 的错误。

您可以在内存中执行联合:

db1.SomeTable.AsEnumerable().Union(db2.SomeTable.AsEnumerable())

如果你想在数据库中执行联合,你需要使用原始 SQL,或者将一些表映射到 DBML 中的另一个数据库,或者使用表值函数或 View 。

关于c# - 具有未知数据类型的 LINQ 的 .Union(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37592095/

相关文章:

sql-server - 从 SQL 存储过程导出文本文件

c# - 链接 LINQ 查询时速度缓慢

c# - 如何从 Action() 返回值?

c# - 访问修改后的闭包 : ReSharper

c# - C#获取上一页URL的方法

sql - 将大型 sql 脚本分成较小的批处理有好处吗?

c# - 手动将 LINQ 查询语法转换为 Lambda 表示法

c# - EntityFramework 引用回调用方 - 找到的程序集的 list 定义与程序集引用不匹配

c# - 有没有一种方法可以在 TreeView.Nodes 集合中搜索 TreeNode.Text 字段?

php - 使用 PHP (Linux) 连接到 MSSQL