views:

65

answers:

2

Hi, I am trying to build a dynamic predicate with Entity Framework by mapping an enum to the column field:

In the where clause i have entered ?? as i am not sure what to put there, i want this be dynamic like in this article, although that doesn't work me in EF on;y linq to sql:

http://stackoverflow.com/questions/2497303/how-to-specify-dynamic-field-names-in-a-linq-where-clause

For example:

I have an enum:

public enum SearchTypes {

  FirstName = CustFName,
  LastName = CustLName

}

My method is as such:

private static IEnumerable<CustomerSearchInfo> GetCustomers(String customerName, SearchType searchType)
    {
        using (var context = new NewgenEntities())
        {
            return context.tblCustomers.Where(??).
            Select(p => new CustomerSearchInfo
                            {
                                FirstName = p.CustFName,
                                LastName = p.CustLName,
                                Id = p.CustID,
                                EmailAddress = p.CustEmail,
                                Mobile = p.CustMNumber,
                                Phone = p.CustPNumber
                            }).ToList();
        }

Has anyone got a way of building an expression based on a enum?

+1  A: 

Check out this post for using enums with EF. It's a lot to go through but it works.

Another approach is to create 1 property that is an enum (let's call it SearchType) and then another integer property called SearchTypeId. The enum property encapsulates the Id property like this:

public SearchType SearchType
{
    get
    {
        return (SearchType)this.SearchTypeId;
    }

    set
    {
        this.SearchTypeId = (int)value;
    }
}

Yes, this is also ugly - but it works.

In the next version of EF, it will support enums but this obviously doesn't do you too much code right now.

Steve Michelotti
A: 

Check my answer to this question to see how to build a dynamic linq query with Expression.

Danny Chen