2

I'm using EF code first in my project, I have following entity:

public class WorkcenterCapacity : ITimePeriodEntity
{
    public int Id { get; set; }
    public decimal AvailableCapacity { get; set; }
    public DateTime FromTime { get; set; }
    public DateTime ToTime { get; set; }
}
public interface ITimePeriodEntity
{
    DateTime FromTime { get; set; }
    DateTime ToTime { get; set; }
}  

I used PredicateBuilder to make a dynamic predicate too. I defined following generic class for usability purpose:

public static class CropPredicateBuilder<T> where T : ITimePeriodEntity
{
    public static Expression<Func<T, bool>> Creat(DateTime windowStart,
                                                  DateTime windowFinish)
    {
        var result = PredicateBuilder.False<T>();
        Expression<Func<T, bool>> completelyInWindowRanges =
            x => x.FromTime >= windowStart && x.ToTime <= windowFinish;
        Expression<Func<T, bool>> startIsInWindowRanges =
            x => x.FromTime >= windowStart && x.FromTime <= windowFinish;
        Expression<Func<T, bool>> finishIsInWindowRanges =
            x => x.ToTime >= windowStart && x.ToTime <= windowFinish;
        Expression<Func<T, bool>> overlapDateRangeWindow =
            x => x.FromTime <= windowStart && x.ToTime >= windowFinish;

        return result.Or(completelyInWindowRanges)
            .Or(startIsInWindowRanges)
            .Or(finishIsInWindowRanges)
            .Or(overlapDateRangeWindow);
    }
}

and use it as following:

var predicate = CropPredicateBuilder<WorkcenterCapacity>
               .Creat(DateTime.Now,DateTime.Now.AddDays(10));

var workcenterCapacities = dbContext.WorkcenterCapacities
            .AsNoTracking()
            .Where(predicate)
            .AsExpandable()
            .ToList();

but when I run it, I get following error:

Unable to cast the type 'WorkcenterCapacity' to type 'ITimePeriodEntity'. LINQ to Entities only supports casting EDM primitive or enumeration types.

How can I solve this problem?

Masoud
  • 8,020
  • 12
  • 62
  • 123

2 Answers2

1

Try like this

where T : class, ITimePeriodEntity

It is wanting first constraint be class. I think it is want be sure.

Masoud
  • 8,020
  • 12
  • 62
  • 123
umut özkan
  • 132
  • 1
  • 8
0

By the way this would also do the trick and is probably faster.

public static class CropPredicateBuilder<T> where T : class, ITimePeriodEntity
{
    public static Expression<Func<T, bool>> Creat(DateTime windowStart,
                                                  DateTime windowFinish)
    {
        var result = PredicateBuilder.False<T>();
        Expression<Func<T, bool>> startBeforeToTime =
            x => windowStart <= x.ToTime;
        Expression<Func<T, bool>> finishAfterFromTime =
            x =>  windowFinish >= x.FromTime;

        return result.Or(startBeforeToTime)
            .Or(finishAfterFromTime);
    }
}
Ronald Emergo
  • 31
  • 1
  • 8