I have this generic class that uses Entity Framework 6.x.
public class GenericRepository<TEntity, TId> where TEntity, class, IIdentifyable<TId> { public virtual TEntity GetById(TId id) { using (var context = new DbContext()) { var dbSet = context.Set<TEntity>(); var currentItem = dbSet.FirstOrDefault(x => x.Id == id); return currentItem; } } public virtual bool Exists(TId id) { using (var context = new DbContext()) { var dbSet = context.Set<TEntity>(); var exists = dbSet.Any(x => x.Id == id); return exists ; } } }
And these interfaces:
public interface IIdentifyable : IIdentifyable<int> { } public interface IIdentifyable<out TId> { TId Id { get; } }
And objects that look like this:
public class CustomerEntity : IIdentifyable<int> { public string Name { get; set; } public int Id { get;set; } } public class ProductEntity : IIdentifyable<Guid> { public string Name { get; set; } public Guid Id { get;set; } }
My problem is that it does not compile. I get this error:
Cannot apply operator ' == ' to operands of type ' TId ' and ' TId '
I tried changing it to x => Equals(x.Id, id) , but then EF will not be able to translate it. Anyway?
I know that instead of FirstOrDefault I can use Find() . But I need it more than the methods mentioned above. Is there any way to match EF TId with TId ? TId is currently only guid and int . I have already seen the questions below, but they do not cope with the problem of translating to SQL.
Is it impossible to apply the == operator to generic types in C #?
How to solve Operator '! = 'cannot be applied to operands of types T and T.
generics c # entity-framework
smoksnes
source share