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:
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, S开发者_JAVA百科earchType 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?
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.
精彩评论