例如,假设我有4个不同的实体,每个实体都实现将实体添加到数据库的Add()方法:
public class Profile
{
...
public void Add()
{
this._dbContext.Profile.Add(this);
this._dbContext.SaveChanges();
}
...
}
现在,我想拥有一个通用类,该通用类在一个抽象类中而不是X个类中实现这种行为。所以我尝试了以下方法:
public abstract class Entity<TEntity> where TEntity : class
{
protected DbContext _dbContext;
protected Entity()
{
this._dbContext = new SMTDBContext();
}
public void Add()
{
this._dbContext.Set<TEntity>().Add(this);
this._dbContext.SaveChanges();
}
}
当然,它不会担心,因为“ this”不是TEntity ...但是将来会!到目前为止,我一直试图寻找一个做类似的事情但没有成功的人。
您的问题的解决方案是使用通用约束的定义更明确。定义约束,因为TEntity必须是Entity <TEntity>的子类,即使用where TEntity : Entity<TEntity>
代替where TEntity : class
public abstract class Entity<TEntity> where TEntity : Entity<TEntity>
{
protected DbContext _dbContext;
protected Entity()
{
this._dbContext = new SMTDBContext();
}
public void Add()
{
this._dbContext.Set<TEntity>().Add((TEntity)this);
this._dbContext.SaveChanges();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句