Linq 2 SQL - Generic where where

Is there any way to do this

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

Please note: i.Id does not exist in context, since linq does not know which object it works with, and Id is the primary key of the table

+5
source share
4 answers

(remote approach tied to attributes)

edit: and here is the metamodel path (therefore, it works with mapping files, as well as with attributes):

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);
}
+4
source

You will need to create the appropriate interface from which the entities are derived (if you do not want to do this using an expression tree, for example, the Marc 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();
}
+2
source
0
var X = _db.table.Select(i => i.Id == id);

IQueryable < >

0

All Articles