c# - 编译查询失败 - 查询是针对与指定 DataContext 关联的映射源不同的映射源编译的

标签 c# sql .net sql-server linq-to-sql

我有以下代码用于编译的 Linq2sql 查询以计算表中的行数。尽管相同的未编译查询运行顺利,但查询抛出异常:

public static Func<ServiceCustomContext, int> CompiledCount
    = CompiledQuery.Compile((ServiceCustomContext db) => db.Current.Count());
public static int Count()
{
    using (ServiceCustomContext db = new ServiceCustomContext(Constants.NewSqlConnection))
        return CompiledCount(db);
}

ServiceCustomContext 继承自 DataContext 并且只有(除了构造函数)Table 包括一个名为 Current 的表在上面的示例中使用。

我得到以下异常:

'Query was compiled for a different mapping source than the one associated with the specified DataContext.'

这仅在使用如上所述的已编译 查询时才会发生。只要我有一个简单的:

return db.Current.Count();

Count() 方法中,一切正常。

我不明白这是怎么回事。我认为可能是我需要保留对 DataContext (ServiceCustomContext) 的引用,尽管这似乎违反直觉,但即使是 the Microsoft examples不要那样做。我找到的唯一解释是 here这基本上是上面链接中 Microsoft 示例中提到的编译查询确实是错误的。不过我怀疑这是真的。

最佳答案

如果您在应用程序的生命周期内仅使用一次 Count(),代码将运行良好。错误的意思正是它所说的。如果您查看 CompiledQuery 的代码:

    private object ExecuteQuery(DataContext context, object[] args) {
        if (context == null) {
            throw Error.ArgumentNull("context");
        }
        if (this.compiled == null) {
            lock (this) {
                if (this.compiled == null) {
                    this.compiled = context.Provider.Compile(this.query);
                    this.mappingSource = context.Mapping.MappingSource;
                }
            }
        }
        else {
            if (context.Mapping.MappingSource != this.mappingSource)
                throw Error.QueryWasCompiledForDifferentMappingSource();
        }
        return this.compiled.Execute(context.Provider, args).ReturnValue;
    }

您可以看到它的作用,它实际上仅在首次调用时才编译查询。它还会保存对您的 DataContext.Mapping.MappingSource 的引用,并确保您在每次后续调用中使用相同的 MappingSource

默认情况下,每次创建新的 DataContext 时,都会同时创建一个新的 MappingSource。这是在构造函数中完成的,以后无法覆盖它,因为 DataContext.MappingMetaModel.MappingSource 属性只有一个公共(public) getter。但是,有一个 DataContext 的构造函数重载,它将 MappingSource 作为参数,这(幸运的是)允许您在应用程序的整个生命周期中重用单个映射源。

不确定您的 ServiceCustomContext 类的确切构造函数是什么,但以下代码应该为您提供防止错误发生的解决方案提示:

public class ServiceCustomContext : DataContext
{
    private static readonly MappingSource mappingSource = new AttributeMappingSource();

    public ServiceCustomContext(string connection) : base(connection, mappingSource)
    {
    }
}

我假设您使用属性来声明映射,但是如果您使用 XML 文件进行数据库映射,则可以使用 XmlMappingSource

关于c# - 编译查询失败 - 查询是针对与指定 DataContext 关联的映射源不同的映射源编译的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53696163/

相关文章:

.net - 针对多个框架的 dotnet 包

.net - 无法创建全屏WPF弹出窗口

c# - 如何从 Windows 窗体中的图表中删除网格线?

mysql - 从以前的最新记录中选择一列

.net - NuGet 自动包还原不适用于 MSBuild

java - getWritableDatabase 导致 nullpointerException

python - 使用 python 从 Azure 机器学习服务连接 Azure SQL 数据库时出错

c# - 在 C#/.NET 中将字符串转换为整数

c# - 如果编译器可以对整数文字执行隐式缩小转换,那么它也应该

c# - 为什么两个多重绑定(bind)中只有一个有效?