0
public abstract class BaseEntity<T>
{
    public T? Id { get; set; }
}
public interface IDocumentRepository<TDocument, TId> where TDocument : BaseEntity<TId>
{
    Task<TDocument> FindByIdAsync(TId id);
}

Is this code can be implemented without passing TId in at the IDocumentRepository interface?
So something like this:

public interface IDocumentRepository<TDocument> where TDocument : BaseEntity<T>
{
    Task<TDocument> FindByIdAsync(T id);
}
quywsx
  • 53
  • 8
  • Sounds like an X/Y problem. Why do you need it? – AgentFire Aug 24 '23 at 12:46
  • It would be a bit cleaner in my opinion but curiosity too. – quywsx Aug 24 '23 at 13:05
  • Mayhaps it would be cleaner, but most definetely wouldn't be **clearer**, which is not good. Also, C# doesn't work that way, if you're referencing a generic type, you should also speficy the generic's type argument. There are things like open generics, but they exist only in the reflection. – AgentFire Aug 24 '23 at 13:11

1 Answers1

0

If I'm understanding correctly, you need to implement repository pattern and at the same time abstract away the primary key for your entities. Maybe this helps.

interface IBaseEntity<TKey>
{
    public TKey Id { get; set; }
}

interface IRepositoryBase<TEntity, TEntityKey> where TEntity : class, IBaseEntity<TEntityKey>
{
    Task<TEntity> FindByIdAsync(int id);
}

class DocumentRepository<T> : IRepositoryBase<T, Guid> where T : class, IBaseEntity<Guid>
{
    public Task<T> FindByIdAsync(int id)
    {
        throw new NotImplementedException();
    }
}
Yoss
  • 428
  • 6
  • 16