Search code examples
c#entity-frameworkdatacontextlinqpad

Directly referencing ObjectContexts like in LinqPad


I'm in the process of moving some code from LinqPad to a regular C# VS2010 environment.

I noticed that in LinqPad, you can just directly use an ObjectContext (i.e. using the pluralized table name) whereas in my regular (VS2010) C# code I need to instantiate the ObjectContext first.

To be clearer, say if I have a table called "Categories". To get the count, I can just do the following in LinqPad:

int i = Categories.Count();

But in my own program, I have to do this:

MyEntities dc = new MyEntities();
int i = dc.Categories.Count();

How can I achieve that extra convenience in my own program? I feel like I'm missing some fundamental stuff...

Thanks for the help!


Solution

  • LINQPad achieves this by subclassing your typed ObjectContext. You could do the same in VS if you wanted, although it could end up cluttering your class and is arguably bad design because you don't need access to any of the protected members of the object context.

    If you just want a consistent means of writing your queries in LINQPad vs VS, you can easily create an equivalent variable in LINQPad as follows:

    var db = this;
    int i = db.Categories.Count();