0

I'm trying to figure out if there is a way to use the type defined in one generic when defining another generic. Here is the general structure of my entities.

public class BaseEntity<T>
{
    T Id {get; set;}
}

public class Company : BaseEntity<int>
{ 

}

Notice that when defining a "Company" I specify the Id type of "int". I do this because the Id of each entity may vary by type, e.g. int, guid, long, string etc.

My question arises as I'm creating generic services that will be defined against these entities, e.g.

public class EntityService<Tentity> where Tentity : BaseEntity
{
    public IEnumerable Read(Tentity.Id?? id)
    {
    }
}

The crux of my question is there a way I can retrieve the type of my Id defined in the entity (it's type "int" above), and use that when defining my service, rather than having to redefine?

Right now I have to do this.

var companyService = new EntityService<Company, int>();

I'd rather just do this, since "int" is already defined within the "Company" entity.

var companyService = new EntityService<Company>();

Lastly, I understand I could switch my code to have a generic flow through all the way from the EntityService to the actual BaseEntity, however my entities are tied to this Id type in the underlying data, and it does not make sense to me to not define it within the actual entity as it will not change.

Workaround: I have to respecify a type to be used from within EntityService, e.g.

public class EntityService<Tentity, TIdType> where Tentity : BaseEntity  where TIdType : struct, IConvertible
{
    public IEnumerable Read(TIdType id)
    {
    }
}

Here's the kicker, when I box these generic parameters in EntityService, C# gripes at compile time if I don't in fact provide an "int" for EntityService, however I'm not able to grab this type and use it from within my EntityService class without redefining it.

raterus
  • 1,980
  • 20
  • 23
  • 1
    what is `CompanyService`? and please correct your `EntityService` code – ingvar Apr 14 '19 at 15:11
  • 2
    You should define a generic argument in order to use it as a type substitution. So the entity service should be like `EntityService where TEntity : BaseEntity { public TId Id { get; set; } }` and the company service like `CompanyService : EntityService {}` – tukaef Apr 14 '19 at 15:18

0 Answers0