【发布时间】:2026-02-24 15:40:01
【问题描述】:
我有以下两个通用类:
public abstract class Entity<T> : IEntity<T>, IAuditableEntity,ISoftDeletable where T : struct
{
public T Id { get; set; }
public DateTime CreatedDate { get; set; }
public string CreatedBy { get; set; }
public DateTime UpdatedDate { get; set; }
public string UpdatedBy { get; set; }
public bool Deleted { get; set; }
}
public abstract class Repository<TEntity,TKey> : IRepository<TEntity, TKey> where TEntity :Entity<TKey> where TKey : struct
{
protected DbContext Context;
protected readonly IDbSet<TEntity> Set;
protected Repository(DbContext context)
{
Context = context;
Set = Context.Set<TEntity>();
}
public TEntity Get(TKey key)
{
var output = Set.FirstOrDefault(o => o.Id.Equals(key));
return output ;
}
}
我的问题是 Get 方法。我不断收到此错误
无法创建“System.Object”类型的常量值。仅有的 在此上下文中支持原始类型或枚举类型。”
我尝试使用 == 但它不会编译并说
不能将 == 应用于操作数 TKey 和 TKey
为什么这不起作用?我的 TKey 应该是原始数据类型,不是 TKey:struct 正确的限制器吗?
为什么有Equals(int)的时候编译器还要用Equals(object),也就是这个key是什么?
【问题讨论】:
-
您的
IDbSet不知道TKey的任何内容,因此它不能将==应用于属性Id(我怀疑它的类型是TKey)。 -
怎么样,如果我保护了只读 IDbSet
Set;哪里 TEntity :Entity where TKey : struct ?? -
嗯,id 是 1,我不知道你为什么怀疑 Id 是 TKey 类型。需要详细说明吗?
-
o.Id 属于 T 类型(至少它在您的实体声明中说,key 属于 TKey 类型。
-
@DevilSuichiro:用作约束参数的名称与方法参数的名称一样没有意义。您不需要在两个单独的声明中使用相同的名称。在这种情况下,
Repository的声明表明第一个约束参数TEntity的类型必须为Entity<TKey>,因此第二个约束参数 (TKey) 成为Entity<T>的第一个/唯一约束参数。
标签: c# entity-framework generics struct