【问题标题】:LINQ to Entities and castingLINQ to Entity 和铸造
【发布时间】:2013-03-15 16:03:31
【问题描述】:

我有一些具有 CategoryId 成员的 EF 代码第一类,该成员也在名为 ICategoryFilterable 的接口中定义。

    public class One : ICategoryFilterable
    {
        public int CategoryId { get; set; }
        /* more properties here */
    }

    public class Two : ICategoryFilterable
    {
        public int CategoryId { get; set; }
        /* more properties here */
    }

    public interface ICategoryFilterable
    {
        int CategoryId { get; set; }
    }

现在,我想按指定类别从数据库中检索记录。我为此创建了一个通用方法,但它不起作用,我找不到解决方案。

    private IQueryable<T> FilterByCategory<T>(IQueryable<T> items, IEnumerable<int> filter)
        where T : ICategoryFilterable
    {
        return from item in items
               where filter.Contains(item.CategoryId)
               select item;
    }

无法将类型“MyNamespace.One”转换为类型“MyNamespace.ICategoryFilterable”。 LINQ to Entities 仅支持转换 EDM 基元或枚举类型。

【问题讨论】:

    标签: c# .net entity-framework linq-to-sql entity-framework-5


    【解决方案1】:

    应该工作......

    您可以使用委托来选择适当的类别 ID:

        private IQueryable<T> FilterByCategory<T>
                    (IQueryable<T> items, IEnumerable<int> filter, 
                     Func<T, int> categorySelector)
        {
            return items.Where(i => filter.Contains(categorySelector(i)));
        }
    

    快速使用示例:

            var source = Enumerable.Empty<One>().AsQueryable();
            var filter = Enumerable.Empty<int>();
    
            var filtered = FilterByCategory(source, filter, s => s.CategoryId);
    

    【讨论】:

    • 请查看我的更改。但是,这也不起作用(阅读异常)。
    • 您能否在您的问题中添加一个 FilterByCategory 方法调用的示例?
    • IEnumerable 只是一个整数列表。这不是问题。它无法将One 转换为ICategoryFilterable 以从数据库中获取正确的记录。
    • 我认为如果不事先枚举内存源,您将无法执行此操作。我已编辑我的答案以提供替代解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 2010-12-06
    • 2012-10-26
    • 2019-06-01
    • 2010-10-30
    • 1970-01-01
    相关资源
    最近更新 更多