找不到源类型'System.Data.Entity.DbSet'的查询模式的实现

Fyl*_*lax 23 c# linq entity-framework

我是第一次使用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; 

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在查询行(确切地说"set"变量用红色下划线)我得到错误:

无法找到源类型'System.Data.Entity.DbSet'的查询模式的实现.'选择'未找到.缺少'System.Linq'的引用或using指令

MyDbEntities是由Entity Framework在Database-First方法中自动生成context.TablesDbSet,因此它应该能够使用Linq,它已经通过该using指令添加了.为了避免误解,我在本课程中找到以下内容:

public virtual DbSet<MyTable> Tables { get; set; }
Run Code Online (Sandbox Code Playgroud)

为了完成这项select工作,我错过了什么?

谢谢.

Kri*_*hna 35

您需要添加对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
            }
        }
     }
}
Run Code Online (Sandbox Code Playgroud)

  • 在我的情况下,我需要引用System.Linq (13认同)
  • 在使用Linq2SQL时,应该完成对System.Data.Linq的引用,在所有其他情况下,设置对System.Linq的引用. (3认同)

Not*_*Fun 16

刚刚添加了一个参考 using System.Linq;并且工作正常,如上所述。