Search code examples
c#entity-frameworkef-code-firstlinq-to-entitiespredicatebuilder

Unable to cast the type A to type B. LINQ to Entities only supports casting EDM primitive or enumeration types


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?


Solution

  • Try like this

    where T : class, ITimePeriodEntity
    

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