tags:

views:

176

answers:

3

for instance a very simple method:

private int GetCount(ITable table) {

  return (from T in table select T).Count();
}
+4  A: 

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?

Mehrdad Afshari
excellent. But how can i use where clause? private int GetCount<T>(IQueryable<T> table, int intID) { return (from T in table where table.ID == intID select T).Count(); }
Fırat KÜÇÜK
Yeah, that works, but you can simply use lambda expressions directly: `table.Where(row => row.Id == id).Count()`
Mehrdad Afshari
i cannot access row.id.
Fırat KÜÇÜK
@firatkuck why can't you access the row Id? If you can't access it you are out of luck.
David Basarab
A: 

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);
}
Marc Gravell
thanks good solution.
Fırat KÜÇÜK
A: 

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.

Beatles1692