EntityFramework : FindBy (column name) select arbitrary column by expression tree

c# entity-framework entity-framework-6 linq

Question

I have a very simple code of what I am trying to achieve here.

Basically the idea here would be to be able to do a simple FindBy(x => x.<the_column_name>, <the value>); therefore I wouldn't have to copy-paste the same query by changing only the column name.

For now I keep getting an exception from LINQ saying LINQ to Entities does not recognize the method 'System.String Invoke(Spunky.Entities.User)' method, and this method cannot be translated into a store expression

Is that something possible ? Or maybe we're not yet there with EF 6.1?

public class UsersRepository
{
  private Lazy<IDataContext> context;

  public UsersRepository()
    : this(() => new DataContext())
  {
  }

  public UsersRepository(Func<IDataContext> context)
  {
    this.context = new Lazy<IDataContext>(context);
  }

  public IQueryable<User> Find(int id)
  {
    return FindBy(u => u.Id, id);
  }

  public IQueryable<User> Find(string username)
  {
    return FindBy(u => u.Username, username);
  }

  public IQueryable<User> FindBy<T>(Func<User, T> property, T value)
  {
    return context.Value
            .Users
            .Where(u => property.Invoke(u).Equals(value));
  }
}
1
1
4/6/2014 8:12:33 PM

Popular Answer

If you change the signature

IQueryable<User> FindBy(Expression<Func<User, bool>> predicate)
{
    return context.Users.Where(predicate);
}

you can call

return FindBy(u => u.Username == username);

The code hardly changes, but you don't need to manufacture expressions.

You have to enter an expression (not a Func) because expressions can be translated into SQL. A Func is just a .Net delegate, for which no SQL equivalent exists.

1
4/6/2014 9:28:30 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow