LINQ to Entities 仅支持使用 IEntity 接口转换 EDM 原语或枚举类型 [英] LINQ to Entities only supports casting EDM primitive or enumeration types with IEntity interface

查看:22
本文介绍了LINQ to Entities 仅支持使用 IEntity 接口转换 EDM 原语或枚举类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下通用扩展方法:

I have the following generic extension method:

public static T GetById<T>(this IQueryable<T> collection, Guid id) 
    where T : IEntity
{
    Expression<Func<T, bool>> predicate = e => e.Id == id;

    T entity;

    // Allow reporting more descriptive error messages.
    try
    {
        entity = collection.SingleOrDefault(predicate);
    }
    catch (Exception ex)
    {
        throw new InvalidOperationException(string.Format(
            "There was an error retrieving an {0} with id {1}. {2}",
            typeof(T).Name, id, ex.Message), ex);
    }

    if (entity == null)
    {
        throw new KeyNotFoundException(string.Format(
            "{0} with id {1} was not found.",
            typeof(T).Name, id));
    }

    return entity;
}

不幸的是,Entity Framework 不知道如何处理 predicate,因为 C# 将谓词转换为以下内容:

Unfortunately Entity Framework doesn't know how to handle the predicate since C# converted the predicate to the following:

e => ((IEntity)e).Id == id

Entity Framework 抛出以下异常:

Entity Framework throws the following exception:

无法将类型IEntity"转换为类型SomeEntity".LINQ到实体仅支持转换 EDM 原语或枚举类型.

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

我们如何让实体框架与我们的 IEntity 接口一起工作?

How can we make Entity Framework work with our IEntity interface?

推荐答案

我能够通过向扩展方法添加 class 泛型类型约束来解决这个问题.不过,我不确定它为什么有效.

I was able to resolve this by adding the class generic type constraint to the extension method. I'm not sure why it works, though.

public static T GetById<T>(this IQueryable<T> collection, Guid id)
    where T : class, IEntity
{
    //...
}

这篇关于LINQ to Entities 仅支持使用 IEntity 接口转换 EDM 原语或枚举类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆