【问题标题】:Linq to SQL intellisense has no knowledge of tables within the datacontext objectLinq to SQL intellisense 不知道 datacontext 对象中的表
【发布时间】:2011-05-02 23:33:20
【问题描述】:

我可以使用我的 datacontext 对象成功连接到数据库。我能够成功地读取和写入数据库,但是我不能使用其他人使用的相同语法。

例如,当我想从表中获取数据时,我必须这样做:

db = new UserDataDataContext(WebConfigurationManager.ConnectionStrings["UserData"].ConnectionString);
IQueryable Users = db.GetTable<User>();

我希望能够像我看到其他人那样编写 linq 查询:

db = new UserDataDataContext(WebConfigurationManager.ConnectionStrings["UserData"].ConnectionString);
var query = from u in db.User
            where u.UserName == "Test"
            select u;

但智能感知不将 User 识别为 db 的属性,因此无法编译。 Intellisense 不显示任何看起来与我的数据库的表或实体相关的属性。

这是我收到的错误消息:

'System.Data.Linq.DataContext' does not contain a definition for 'User' and no extension method 'User' accepting a first argument of type 'System.Data.Linq.DataContext' could be found (are you missing a using directive or an assembly reference?)

这是我正在做的事情的概要:

我使用数据库设计器,将我想要的表格拖入其中。

然后我将它保存为 dbml 文件。

然后它为我创建了扩展 dataContext 的新类,名为 UserDataDataContext。然后我实例化一个名为 db 的新 UserDataDataContext 实例,从 Web.config 传入我的连接字符串。

然后我尝试编写一个 linq 查询,引用表名作为 db 对象的属性,但它无法识别它们。

与我读过的所有示例相比,我似乎找不到我做错了什么。有什么想法吗?

【问题讨论】:

    标签: sql linq linq-to-sql datacontext


    【解决方案1】:

    我确定您在某处有以下变量声明:

    // variable is of type System.Data.Linq.DataContext
    DataContext db;
    

    改成:

    // variable is now of the appropriate subclass's type
    UserDataDataContext db;
    

    如果db 是一个局部变量,并且您可以将初始化和声明一起内联,那么使用隐式类型会更好:

    // db is implicitly of type UserDataDataContext
    var db = new UserDataDataContext(WebConfigurationManager.ConnectionStrings["UserData"].ConnectionString);
    

    C# 是一种安全静态类型的语言。尽管您的引用所引用的对象确实在运行时具有您所期望的属性,但编译器不会让它编译,因为这些属性不存在于 变量的类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-19
      相关资源
      最近更新 更多