for instance a very simple method:
private int GetCount(ITable table) {
return (from T in table select T).Count();
}
for instance a very simple method:
private int GetCount(ITable table) {
return (from T in table select T).Count();
}
You mean something like this?
private int GetCount<T>(IQueryable<T> table) {
// return (from T in table select T).Count();
return table.Count();
}
Why don't you call Count()
directly on the object, by the way?
Re your comment:
private int GetCount(IQueryable table, int intID)
Is that the PKID? Shouldn't the answer be 0 or 1? Anyway... you would have to build the Expression
dynamically. Something like (untested, based on this):
static TEntity GetCount<TEntity>(this DataContext ctx, int key) where TEntity : class
{
return GetCount<TEntity, int>(ctx, key);
}
static TEntity GetCount<TEntity, TKey>(this DataContext ctx, TKey key) where TEntity : class
{
var table = ctx.GetTable<TEntity>();
var pkProp = (from member in ctx.Mapping.GetMetaType(typeof(TEntity)).DataMembers
where member.IsPrimaryKey
select member.Member).Single();
ParameterExpression param = Expression.Parameter(typeof(TEntity), "x");
MemberExpression memberExp;
switch (pkProp.MemberType)
{
case MemberTypes.Field: memberExp = Expression.Field(param, (FieldInfo)pkProp); break;
case MemberTypes.Property: memberExp = Expression.Property(param, (PropertyInfo)pkProp); break;
default: throw new NotSupportedException("Invalid primary key member: " + pkProp.Name);
}
Expression body = Expression.Equal(
memberExp, Expression.Constant(key, typeof(TKey)));
var predicate = Expression.Lambda<Func<TEntity, bool>>(body, param);
return table.Count(predicate);
}
Linq contains this amazing IQueryable interface that lets us to extend a query without actually sending any query to data base.This way you can pass your query around in your application safe and sound and every class that really needs the actual data sends the actual query to the db. For example you have a method that returns a query of all users:
public IQueryable<User> GetAll()
{
return from user in dbContext.Users select user;
}
and you want to get avtive users only.here's what you can do
foreach(var activeUser in (from user in UserRepository.GetAll() where user.Active==true select user).List())
{
//do something;
}
In above example List() method will cause Linq to send a query to the database.