Working with DataContext.GetTable<T>() to get a 'QueryProvider'
The DataContext.GetTable() method will return an object of type:
System.Data.Linq.Table
By doing that, I presume I haven't issued a call to the database to retrieve the entire table. Otherwise, LINQ would be somewhat inefficient.
Therefore, all I have done is drill into my strongly typed Datacontext class (eg, dbDataContext) to grab a handle on, for example, its "Customers" property, that represents the Customers table in SQL Server.
I can then get an IQueryable off the object returned by GetTable() and still not have hit the database. Ie, my 'Service Layer' code will be LINQ to Objects rather than Linq to Sql.
By doing all this, I will reduce the number of repositories that I need.
Question:
Are the above assumptions correct?
Note:
开发者_JAVA技巧I am trying to figure out a way to build my Queries using interfaces and generics to make it testable and all that doo dah.
So, thinking along the lines of @zowen's response to:
Repository pattern: One repository class for each entity?
I am trying to implement
public interface IQueryProvider<T>
{
TResult Query<TResult>(Func<IQueryable<T>, TResult> query);
}
I know not strictly necessary, but I am going through the learning curve and looking at the architectural options that suit me and how I think.
What I'm trying to do:
I am trying to implement the following for SQL Server instead of MongoDb:
public class MongoQueryProvider<T> : IQueryProvider<T>
{
private readonly IMongoCollection<T> collection;
public MongoQueryProvider(IMongoDatabase database)
{
this.collection = database.GetCollection<T>();
}
public TResult Query<TResult>(Func<IQueryable<T>, TResult> query)
{
return query(this.collection.Linq());
}
}
What I want is to get a handle on GetTable() and then write my Service Layer Linq code against that.
I suspect I will have to write a wrapper interface to get the equivalent of the IMongoDatabase database variable.
However, the question is the one above, not this other issue. Like I say, I'm just learning here. No production code will be hurt in this movie.
The short answer to your question is that your assumptions are correct. You do not access the database through the GetTable<>()
method of the DataContext
. And, when you get an IQueryable
you also don't access the database until you enumerate on it.
Also, see if this helps you on your quest: Advantage of creating a generic repository vs. specific repository for each object?
精彩评论