【问题标题】:Entity Framework Include fails to compile实体框架包含无法编译
【发布时间】:2012-07-18 08:57:34
【问题描述】:

我通过 DbContext 生成器生成了我的实体,并将其添加到使用我的实体上下文模型的 API 控制器中。但是下面的方法编译失败:

public IEnumerable<casino> Getcasinos()
    {
        var casinos = db.casinos.Include(c => c.city).Include(c => c.state);
        return casinos.AsEnumerable();
    }

编译器说:

Cannot Convert Lambda Expression to Type 'String' Because It Is Not A Delegate Type

任何想法为什么会这样说?我已导入 System.Linq 命名空间。

【问题讨论】:

    标签: entity-framework asp.net-web-api


    【解决方案1】:

    这实际上是由于ObjectQuery(T).Include 方法而发生的。这具有函数签名:

    public ObjectQuery<T> Include(string path);
    

    您看到这种情况的原因可能是因为无论您在哪里调用它都没有可用的System.Data.Entity 命名空间。从DbExtensions 元数据可以看出,Include 使用表达式需要System.Data.Entity 命名空间:

    namespace System.Data.Entity
    {
        [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Casing is intentional")]
        public static class DbExtensions
        {
            public static IQueryable<T> Include<T, TProperty>(this IQueryable<T> source, Expression<Func<T, TProperty>> path) where T : class;
            public static IQueryable<T> Include<T>(this IQueryable<T> source, string path) where T : class;
            public static IQueryable Include(this IQueryable source, string path);
        }
    }
    

    如果您包含System.Data.Entity 命名空间,错误将得到解决。

    【讨论】:

    • @JuniperAsh:没问题。如果您将数据访问封装在单独的层中,这实际上是一个非常容易犯的错误。
    猜你喜欢
    • 2023-04-11
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多