【问题标题】:Compiled Query error: there is no implicit conversion from entities to 'System.Data.Objects.ObjectContext编译查询错误:没有从实体到 'System.Data.Objects.ObjectContext 的隐式转换
【发布时间】:2013-10-24 09:35:40
【问题描述】:

我正在创建一个委托来从数据库中检索所有客户记录。我以这种方式使用了编译查询,但由于某种原因,我在带有 EF 的 Visual Studio 2012 中遇到了这样的错误。

错误:类型“HTML5Basics.NorthwindDataContext”不能用作泛型类型或方法“System.Data.Objects.CompiledQuery.Compile(System.Linq.Expressions.Expression>)”中的类型参数“TArg0”。没有从“HTML5Basics.NorthwindDataContext”到“System.Data.Objects.ObjectContext”的隐式引用转换。

这个错误是什么以及如何解决这个错误?

代码如下:

public static Func<NorthwindDataContext, string, IEnumerable<SimpleCustomer>> CustomersByCity =
            CompiledQuery.Compile<NorthwindDataContext, string, IEnumerable<SimpleCustomer>>(
            (NorthwindDataContext db, string city) =>
            from c in db.Customers
            where c.City == city
            select new SimpleCustomer { ContactName = c.ContactName });

【问题讨论】:

  • 您需要包含引发异常的代码。
  • 我添加了错误代码

标签: c# asp.net entity-framework visual-studio-2012 entity-framework-4


【解决方案1】:

没有从“HTML5Basics.NorthwindDataContext”到“System.Data.Objects.ObjectContext”的隐式引用转换。

表示这两种类型之间没有转换。

在 .NET 4.5 中,EF5 有一个 System.Data.Objects 命名空间,其中包含 CompiledQuery.Compile 函数。 System.Data.Linq 命名空间中也有一个。

他们有不同的签名:

System.Data.Linq 命名空间: (取自 MSDN http://msdn.microsoft.com/en-us/library/bb548737.aspx):

public static Func<TArg0, TResult> Compile<TArg0, TResult>(
Expression<Func<TArg0, TResult>> query)
where TArg0 : DataContext

System.Data.Objects 命名空间(来自 .pdb):

public static Func<TArg0, TResult> Compile<TArg0, TResult> 
(Expression<Func<TArg0, TResult>> query) 
where TArg0 : ObjectContext

基本上你有两个选择:

1) 使用 System.Data.Linq 命名空间中的那个。

2) 将 ObjectContext(或继承的类型)传入 System.Data.Objects 命名空间的版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多