【问题标题】:Unable to create a constant value of type . Only primitive types or enumeration types are supported in this context无法创建类型的常量值。此上下文仅支持原始类型或枚举类型
【发布时间】:2014-10-15 17:59:23
【问题描述】:

我有以下通用检查方法,

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

但是它返回异常:

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

请指教,

非常感谢,

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    尝试通过在方法名称旁边输入类型 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;
    }
    

    【讨论】:

    • 对不起,我应该提到更改 :) 我将编辑我的帖子
    • 您可以将 if 语句更改为 return dbQuery.Any(e =&gt; e == entity);
    猜你喜欢
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多