For example, let say I have 4 different entity that each implement a Add() method that add the entity to the database :
public class Profile
{
...
public void Add()
{
this._dbContext.Profile.Add(this);
this._dbContext.SaveChanges();
}
...
}
Now I would like to have a generic class that implement this kind of behavior in one abstract class instead of X number of classes. So I tried the following :
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();
}
}
Of course it doesnt worrk because "this" is not a TEntity... but it will be in the future! I tried searching for someone who did something similar without success so far.
The solution to your problem is to be more explicit with the definition of the generic constraint. Define the constraint as TEntity must be a sub-class of Entity<TEntity> i.e. use where TEntity : Entity<TEntity>
instead of 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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With