Work on EF,Need to write a custom where
public virtual IEnumerable GetDataByID<TEntity>() where TEntity : class
{
if (this.Context == null)
Initialize<TEntity>();
TContext context = this.Context;
var result = context.CreateObjectSet<TEntity>().Where(GetExpression<TEntity>(5));
return result;
}
public Expression GetExpression<TEntity>(int id) where TEntity : class
{
ParameterExpression e = Expression.Parameter(typeof(TEntity), "e");
PropertyInfo propInfo = typeof(TEntity).GetProperty(EntityInfo<TEntity>.GetPkFieldName(this.Context));//(KeyPropertyName);
MemberExpression m = Expression.MakeMemberAccess(e, propInfo);
ConstantExpression c = Expression.Constant(id, typeof(int));
BinaryExpression b = Expression.Equal(m, c);
Expression<Func<TEntity, bool>> lambda = Expression.Lambda<Func<TEntity, bool>>(b, e);
return lambda;
}
Error:
The best overloaded method match for 'System.Data.Objects.ObjectQuery.Where(string, params System.Data.Objects.ObjectParameter[])' has some invalid arguments
Why my above syntax is not working, how to fix it?
-
6What's the error message?Mikey Mouse– Mikey Mouse2012年12月24日 11:40:25 +00:00Commented Dec 24, 2012 at 11:40
2 Answers 2
The problem is, the result of CreateObjectSet<TEntity> returns an ObjectSet<TEntity> which defines its own Where method which the compiler will attempt to use. The arguments you are providing are not valid for this method, hence the error.
What you want to be using is Linq's Queryable.Where extension method like so:
var predicate = GetExpression<TEntity>(5);
var objectSet = context.CreateObjectSet<TEntity>();
var results = System.Linq.Queryable.Where(objectSet, predicate);
Comments
The best overloaded method match for 'System.Data.Objects.ObjectQuery.Where(string, params System.Data.Objects.ObjectParameter[])' has some invalid arguments
The problem is this line:
var result = context.CreateObjectSet<TEntity>().Where(GetExpression<TEntity>(5));
Infact you're specifing the wrong parameters: ObjectQuery<T>.Where
public ObjectQuery<T> Where(
string predicate,
params ObjectParameter[] parameters
)
Infact you should pass a string.