0
votes

I have the following hierarchy of interfaces:

public interface IEntity { object Key; }
public interface IEntity<TKey> { TKey TypedKey; }

In my repository layer, I have a GetOne method currently defined as such:

public class Repository<TEntity> : IRepository<TEntity>
    where TEntity : IEntity
{
    public TEntity GetOne(object key) { ... }
}

I would like to constrain the argument on the repository to the TKey type specified by the generic interface of the entity. The obvious solution would be:

public class Repository<TEntity, TKey> : IRepository<TEntity, TKey>
    where TEntity : IEntity<TKey>
{
    public TEntity GetOne(TKey key) { ... }
} 

This works, but requires me to specify the TKey explicitly when creating a repository, or injecting it via the interface. What I would like to do is something like this (the following code will not work, though):

public class Repository<TEntity> : IRepository<TEntity>
    where TEntity : IEntity
{
    public TEntity GetOne<TKey>(TKey key) where TEntity : IEntity<TKey> { ... }
}

Is it at all possible to constrain TKey to be the generic parameter of IEntity without specifying it on the class? If so, how would I do that?

1
public class Repository<TEntity> : IRepository<TEntity> where TEntity : IEntity<string> ? - ColinM
@ColinM I could as well define the method as GetOne(string) then. The point is that the key might be an int, a string, a long, or even a composite object. - Maciej Stachowski

1 Answers

1
votes

The closer you can get without passing TEntity and Tkey, for me is:

public interface IEntity
{
    object Key { get; set; }
}

public interface IEntity<TKey> : IEntity
{
    TKey TypedKey { get; set; }
}

public class Repository<TEntity>
    where TEntity : IEntity
{
    public IEntity<TKey> GetOne<TKey>(TKey key)
    {
        ...;
    }
}

I may think about something else later, but for now, I don't think you can do it without passing both generic arguments.

With the interface inheritance, you could just return a TEntity instead of IEntity<TKey>.