I know this is a crazy thing to ask.. but Ill give it a shot 🙂
Is there anyway to build up your linq/query and then later on be able to build even more on it and then execute it.. for instance like this:
public void Test()
{
var k = TestRepo();
k = k.Where(e => e.SomeColumn == someValue);
rp.DataSource = k.Select(t => t.Id);
rp.DataBind();
}
public IEnumerable<ApplicationEntity> TestRepo()
{
using (var x = new MyEntityContext())
{
return from q in x.MyColumn
select q;
}
}
If im not misstaken this whould never work :)… but whouldnt it be just great if you first could “build” the basics of the query and then extend it somemore and then once its finaly ready actually execute it and get the result..
So is there anyway to do this as in the example above with EF or NHibernate.. or both of em?
Thanks in advance!
The trick is not to dispose the
MyEntityContext. For instance, you can cache it for the lifetime of a request and dispose it at the end of an request. This might look like this:The
TestRepomethod than looks like this:Note how the
TestReponow returnsIQueryable. This allows other methods to change the query and only when you start iterating it, the query will get sent to the database.NOTE: Instead of taking a dependency on a static
ContextFactoryclass, you could also inject anMyEntityContextinto types that wish to use it. You can use this by using a technique called Dependency Injection.