Hello I'm trying to create a generic repository pattern class that uses 2 generics in its implementation. The entity type itself (TEntity) and the key/identifier type (TKey).
Problem occurs whenever I try to check for equality of TKey's.
Error: Operator '==' cannot be applied to operands of type 'TKey' and 'TKey'.
Entity.cs
public class Entity<TKey> where TKey : struct, IComparable, IFormattable, IConvertible, IComparable<TKey>, IEquatable<TKey>
{
public TKey Id { get; set; }
}
IRepository.cs
public interface IRepository<TEntity, in TKey> : IDisposable
where TEntity : Entity<TKey>
where TKey : struct, IComparable, IFormattable, IConvertible, IComparable<TKey>, IEquatable<TKey>
{
/// <summary>
/// Get the <typeparamref name="TEntity"/> by id.
/// </summary>
/// <returns>The entity.</returns>
/// <param name="id">Identifier.</param>
TEntity Get(TKey id);
}
Repository.cs
public class NoSQLRepository<TEntity, TKey> : IRepository<TEntity, TKey>
where TEntity : Entity<TKey>
where TKey : struct, IComparable, IFormattable, IConvertible, IComparable<TKey>, IEquatable<TKey>
{
public TEntity Get(TKey id)
{
// error occurs in the line below.
return _context.Get<TEntity>(typeof(TEntity).Name).Find(entity => entity.Id == id).FirstOrDefault();
}
}
This being said, I need my TKey generic to not be constrained to a class. I rather use primitive types (i.e Int).
Can this be achieved or am I doing something wrong ?