无法找到针对源类型'System.Data.Entity.DbSet'的查询模式实现。

27

我第一次使用Entity Framework,但它似乎没有像预期的那样工作。

这是我的代码:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

public static class QueryClass
{
    public static void Query()
    {
        using (var context = new MyDbEntities())
        {
            DbSet<MyTable> set = context.Tables;
            var query = from val in set select value; 

        }
    }
}

在查询行上(即红色下划线正好在“set”变量上方),我遇到以下错误:

找不到“System.Data.Entity.DbSet”的源类型的查询模式实现。 找不到“Select”。缺少对“System.Linq”的引用或使用指令

MyDbEntities 是通过 Entity Framework 在 Database-First 方法中自动生成的,context.Tables 是一个 DbSet,因此应该能够使用 Linq,通过 using 指令添加。为了避免误解,我在这个类中找到了以下内容:

public virtual DbSet<MyTable> Tables { get; set; }

我需要做什么才能让select起作用?

谢谢。


你的项目是否有引用 System.Core? - Krishna
@Krishna 是的,它可以。 - Fylax
1个回答

44

您需要添加对System.Data.Linq的引用

System.Data.Linq是特定于LINQ-SQL的(DataContext等)

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Linq;
using System.Linq;

public static class QueryClass
{
    public static void Query()
    {
        using (var context = new MyDbEntities())
        {

            IQueryable<MyTable> qTable= from t in context.Tables
                                        select t; // can you confirm if your context has Tables or MyTables?
            Console.WriteLine("Table Names:");
            foreach (var t in qTable)
            {
                Console.WriteLine(t.Name);//put the relevant property instead of Name
            }
        }
     }
}

我引用了 System.Data.Linq 并通过 using 指令添加了它,但它仍然给我带来了问题。 - Fylax
抱歉,我的错,我是在VS之外进行操作。请再试一次。还要检查一下你的上下文中是否将表的db set名称命名为MyTables或Tables。 - Krishna
我已经更新了我的问题,解释了Tables和MyTable是什么。无论如何,现在我遇到了一些有趣的事情:VS似乎没有识别IQueryable,尽管System.Linq已经正确加载。我又重新启动了VS(再一次),现在OP中那个烦人的错误已经消失了,完全是随机的。真的,不知道发生了什么。 - Fylax
16
在我的情况下,我需要引用 System.Linq。 - Martin Capodici
3
在使用 Linq2SQL 时应引用 System.Data.Linq,而在所有其他情况下应设置引用为 System.Linq。 - Patrick Peters
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接