Well, I think if you really want to do this, you can try creating your own expression yourself. I assume that you have a base entity class that is shared, and the one where the primary key property is generated. I called this class KeyedEntityBase<TKey> , TKey is the type of key (if you do not have such a class, thatβs fine, the only thing I used for it is a general limitation). Then you can create an extension method like this to create the expression yourself:
public static class Extensions { public static IQueryable<TEntity> WhereIdEquals<TEntity, TKey>( this IQueryable<TEntity> source, Expression<Func<TEntity, TKey>> keyExpression, TKey otherKeyValue) where TEntity : KeyedEntityBase<TKey> { var memberExpression = (MemberExpression)keyExpression.Body; var parameter = Expression.Parameter(typeof(TEntity), "x"); var property = Expression.Property(parameter, memberExpression.Member.Name); var equal = Expression.Equal(property, Expression.Constant(otherKeyValue)); var lambda = Expression.Lambda<Func<TEntity, bool>>(equal, parameter); return source.Where(lambda); } }
And then you can use it like this (for an integer key type):
context.Set<MyEntity>.AsNoTracking().WhereIdEquals(m=>m.Id, 9).ToList();
source share