无法创建类型的常量值。在此上下文中仅支持基元类型或枚举类型

时间:2014-10-15 17:59:24

标签: c# entity-framework

我有以下方法进行通用检查,

public virtual bool CheckExist(T entity)
{
    var context = new eTRdataEntities();
    IQueryable<T> dbQuery = context.Set<T>();
    if (dbQuery.Any(e => e == entity))
    {
        return true;
    }
    return false;
 }

然而它返回异常:

无法创建类型的常量值。在此上下文中仅支持原始类型或枚举类型。

请建议,

非常感谢,

1 个答案:

答案 0 :(得分:0)

尝试通过接受方法名称旁边的类型T来更改代码,如下所示:

public virtual bool CheckExist<T>(T entity)
{
    var context = new eTRIKSdataEntities();
    IQueryable<T> dbQuery = context.Set<T>();
    if (dbQuery.Any(e => e == entity))
    {
        return true;
    }
    return false;
}

您可能还希望仅将类型限制为类,如下所示:

public virtual bool CheckExist<T>(T entity) where T : class
{
    var context = new eTRIKSdataEntities();
    IQueryable<T> dbQuery = context.Set<T>();
    if (dbQuery.Any(e => e == entity))
    {
        return true;
    }
    return false;
}