例如,假设我有 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 的子类即使用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();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)