views:

43

answers:

1

I can successfully connect to the database with my datacontext object. I am able to read and write to the database successfully, however I can't use the same syntax that others appear to be using.

For example, when I want data from a table, I have to do something like this:

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

I'd like to be able to write linq queries like how I see others doing them:

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

But intellisense does not recognize User as an property of db, and thus won't compile. Intellisense doesn't show any properties that look related to tables or entities of my database.

Here is the error message I am getting:

'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?)

Here is a rundown of what I am doing:

I used the database designer, dragged the tables in that I wanted.

Then I saved it as a dbml file.

It then created the new class that extends dataContext for me, named UserDataDataContext. I then instantiate a new instance of UserDataDataContext named db, passing in my connection string from Web.config.

Then I try to write a linq query referencing table names as properties of the db object, but it does not recognize them.

I can't seem to find what I am doing wrong compared to all of the examples I've read. Any ideas?

+3  A: 

I'm sure you have the following variable declaration somewhere:

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

Change it to:

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

If db is a local variable and you can afford to inline the initialization and declaration together, it would be even better to use implicit typing instead:

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

C# is a safe and statically typed language. Although the object referred to by your reference will indeed, at run-time, have the properties you are expecting, the compiler won't let this compile because these properties don't exist on the variable's type.

Ani
Ahh, good call, that was it!
Sgraffite