I have these models class:
public abstract class ModelBase<T>
{
public virtual T Id { get; set; }
}
public class Table: ModelBase<int>
{
public string Name { get; set; }
}
My problem is when I need to work with my repository and I need the type is Table and put the type parameters or constraints:
public class Repository<TEntity>
: IRepository<TEntity> where TEntity
: ModelBase<T> //I know there's a mistake, but as it is needed
How I can do that infers the type that is in Table in this case is int or a reference to it?
TEntity in this case is Table
You were pretty close. In order to use T in your example, you need to provide that type. In order to provide the type, it needs to be passed to the class constructor so it needs to be in the definition. You can include it as like this
public class Repository<TEntity,T>
//^ Include the type in the definition
: IRepository<TEntity> where TEntity
: ModelBase<T>
and now when you instantiate you need to pass both the table, and the table's type
var repo = new Repository<Table,int>();
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