Linq Where the offer with Generics does not remake the basic type Equals

I have the following simple function:

public class BaseEntityRepository<TEntity, TId> : IBaseEntityRepository<TEntity, TId>
    where TEntity : class, TBaseEntity, IIdentifiedEntity<TId>
    where TId : struct {
//...
    public virtual TEntity GetById(TId id) {
        return (from e in GetAll() where e.Id.Equals(id) select e).SingleOrDefault();
    }
//...
}

Since TId is generic, I get the following message:

“It is not possible to create a constant value of type“ System.Object. ”Only primitive types (such as Int32, String, and Guid) are supported in this context.

No matter what type it represents. I tried "Byte", "Int16", "Int32", "Long" ... The message is the same. I thought that defining a general constraint as a structure would be sufficient for the type to be reconstructed as a primitive.

BTW ... GetAll () returns IQueryable<TEntity>.

Anyway ... Does anyone know a workaround? Thanks

+3
2

IEquatable?

where TId : IEquatable<TId>
+4

. , ?

e.Id.GetHashCode() == id.GetHashCode()
-1

Source: https://habr.com/ru/post/1773135/


All Articles