I have the following generic classes:
public class Entity<Key>
{
public Key ID;
}
public interface IEntity<T>
{
T ID { get; set; }
}
public class GenericRepo<TEntity,CEntity,Key>
where TEntity : class, IEntity<Key>
where CEntity : class, IEntity<Key>
{
protected readonly DataContext _context;
protected readonly IMapper _mapper;
public GenericRepo(DataContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public CEntity GetByID(Key id)
{
//here i get operators == cannot be applied to operands of type 'Key' and 'Key'
TEntity dbEntity = _context.Set<TEntity>().FirstOrDefault(e => e.ID == id);
if (dbEntity == null)
{
return null;
}
return _mapper.Map<CEntity>(dbEntity);
}
}
I'm trying to pass a generic type Key
to the ID
property. I'm getting operators == cannot be applied to operands of type 'Key' and 'Key'
when I use ==
on the passed parameter and the Set's property which is also of type Key
, since they are the same generic type Key
, how can I implement equality on Key
on these classes?
the types that I need to pass are int
or string
.
However, I tried adding a where
clause to the class where T : Type
, the operands error removed, but now I cant pass neither string
or int
like the following Entity<int>
i get there is no boxing conversion from int to System.Type
.
I saw some answers like using .Equals
and implementing IComparer to classes, but in my case its a type, and I need ==
to use it in LINQ to SQL in ef-core.
Is there any where
condition to add to the class that I can pass a type to my class and use ==
or any other way?