0

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?

Ali Kleit
  • 3,069
  • 2
  • 23
  • 39
  • 1
    Does this answer your question? [Can't operator == be applied to generic types in C#?](https://stackoverflow.com/questions/390900/cant-operator-be-applied-to-generic-types-in-c) – Wai Ha Lee Apr 13 '20 at 11:02
  • @WaiHaLee I saw that, almost all answers use `EqualityComparer`, i was hoping to find a way to pass `string` or `int` and compare them with `==` without having to go through IComparer or similar interfaces – Ali Kleit Apr 13 '20 at 11:12
  • This [link](https://stackoverflow.com/a/8982693/7086678) maybe helpful for you – Farhad Zamani Apr 13 '20 at 13:22

2 Answers2

0

How to apply == to generic types

You do not. It is a weakness so to say of the .NET type system that generics can not handle operations as operations are defined via static methods.

You pretty much HAVE to go through IComparable or a similar interface.

TomTom
  • 61,059
  • 10
  • 88
  • 148
0

I've ended up using a simple .Equals()

TDataSet dbEntity = _context.Set<TDataSet>().FirstOrDefault(e => e.ID.Equals(id));
Ali Kleit
  • 3,069
  • 2
  • 23
  • 39