In this example, TItem.GetKeyType()
is what I'd like to achieve.
Base CRUD repository interface definition:
ICrudRepository<TItem> where TItem : BaseItem where TKey : TItem.GetKeyType()
public Tkey Id { get; set; }
Base Entity definition:
class BaseItem<TKey>
this.GetKeyType = Tkey.GetType()
Entity implementation:
class Book : BaseItem<Int> //declaration of item's tkey
CRUD Interface implementation:
IBooksRepository : ICrudRepository<Book>
BookRepository : IBookRepository --> Ignorance of key struct
This way, whoever implements BooksRepository is forced to use the entity's implementation struct, int
in this case.
Moreover, I could define new entities using different keys using all the same base entity and crud repository, for example
class Truck : BaseItem<Guid>
Right now there are 2 problems
- In the CRUD interface, I cannot call TItem.GetKeyType(), even if I know that its type is BaseItem, thus it must define this method
- I cannot call TKey.GetType() on BaseItem, even if it must be a struct, thus defining this method
Is there a way to achieve this type of pattern, without having to define multiple BaseEntities and CRUD Repositories for each type of key/struct intended to be used, on a system where keys can be of different types?