无法将类型A强制转换为类型B. LINQ to Entities仅支持强制转换EDM原语或枚举类型

问题描述 投票:2回答:2

我在我的项目中首先使用EF代码,我有以下实体:

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; }
}  

我使用PredicateBuilder制作动态谓词。我为可用性目的定义了以下泛型类:

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);
    }
}

并使用如下:

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

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

但是当我运行它时,我得到以下错误:

无法将“WorkcenterCapacity”类型强制转换为“ITimePeriodEntity”。 LINQ to Entities仅支持转换EDM原语或枚举类型。

我怎么解决这个问题?

c# entity-framework ef-code-first linq-to-entities predicatebuilder
2个回答
1
投票

试试这样吧

where T : class, ITimePeriodEntity

想要第一个约束是类。我认为这是肯定的。


0
投票

顺便说一句,这也可以做到这一点,而且可能更快。

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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.