C#C
C#3y ago
Unmei

Is it possible to build a custom Expression<Func<T, bool>> by chaining "Or" operations to use in EF?

Hi all, this is my first post here.
I want to check if it's possbile to chain Expression.Or operations to be able to use it in EF 6 (Or in a IEnumerable.Where() in general.

Let me explain the context:
  • I have two entities called Orders and Users. Users can create multiple orders, and one Order is related to one single User.
  • Orders have a "CreatedDate" field (so that it is populated with DateTime.Now in the database) and also "CreatedBy" representing the username that created it.
  • Users have a field called "DateDisabled" nullable. When it is
    null
    , I can bring all his orders, but if it has a value, i will just bring orders dating from before he was disabled: order.DateCreated <= user.DateDisabled.
    To simplify:
public class OrderSummaryDpid {
    public int Id { get; set; }
    public DateTime CreatedDate { get; set; }
    public string CreatedBy { get; set; }
}

public class User {
   public DateTime? DateDisabled {get; set;}
   public string UserName {get;set;}
}


a filter to bring orders from a single user would be :
var dateDisabled = user.DateDisabled.HasValue ? userDateDisabled.Value : DateTime.MaxValue; // overkill? yes

Expression<Func<OrderSummaryDpid, bool>> filter = order =>
  order.CreatedDate <= dateDisabled &&
  order.CreateBy == user.UserName;

var userOrders = _repository.Where(filter); // IQueryable<OrderSummaryDpid>


since we can have many users, we would have many filter, one for each user:
var manyUsersOrders = _repository.Where(filter1 || filter2 || filter3 || ... || filterN);

Here comes the question: since it's not known how many users there are in the array, How can I create such an expression that chain
Or
operations like that dinamically?


I tried to build Expressions and use Expression.Or to join them together, but It returns a BinaryExpression and I don't know exactly how to use it to build the final expression. Any help?
Was this page helpful?