John
John

Reputation:

Linq 2 SQL - Generic where clause

Is there a way to do this

public T GetItemById(int id)
{
    Table<T> table = _db.GetTable<T>();
    table.Where(t => t.Id == id);
}

Note that i.Id does not exist in the context as linq does not know what object it is working with, and Id is the primary key of the table

Upvotes: 5

Views: 1933

Answers (4)

Marc Gravell
Marc Gravell

Reputation: 1063058

(removed approach bound to attributes)

edit: and here's the meta-model way (so it works with mapping files as well as attributed objects):

static TEntity Get<TEntity>(this DataContext ctx, int key) where TEntity : class
{
    return Get<TEntity, int>(ctx, key);
}
static TEntity Get<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.Single(predicate);
}

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1501163

You'd need to create an appropriate interface which the entities derive from (unless you want to do it with an expression tree like Marc's example):

public interface IIdentifiedEntity
{
    int Id { get; } // Set as well? Depends on your situation.
}

Then you can write:

public T GetItemById<T>(int id) where T : class, IIdentifiedEntity
{
    Table<T> table = _db.GetTable<T>();
    return table.Where(t => t.Id == id)
                .Single();
}

Upvotes: 2

roman m
roman m

Reputation: 26531

var X = _db.table.Select(i => i.Id == id);

this will return IQueryable< T>

Upvotes: 0

Svish
Svish

Reputation: 158121

Maybe you can find something under Generic Predicates, at http://www.albahari.com/nutshell/predicatebuilder.aspx. It's the last section on the page.

Upvotes: 0

Related Questions