C# 无法创建类型为的常量值。在此上下文中仅支持基元类型或枚举类型
我有以下通用检查方法C# 无法创建类型为的常量值。在此上下文中仅支持基元类型或枚举类型,c#,entity-framework,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; }
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;
}
但是,它返回异常:
无法创建类型为的常量值。在此上下文中仅支持基元类型或枚举类型
请各位指教,
非常感谢,尝试通过在方法名称旁边输入类型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;
}
您可能还希望仅将类型限制为类,如下所示:
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;
}
对不起,我应该提到这个更改:我将编辑我的post。您可以更改if语句以返回dbQuery.Anye=>e==entity;