Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Where clause with Generics does not reconize Equals base type

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 a generic I'm receiving the following message:

"Unable 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 represent. I've tried "Byte", "Int16", "Int32", "Long"... The message is the same. I thought that defining the generic constraint as struct would be enought to the type be reconized as a primitive.

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

Anyway... Does anybody know an workaround? Thanks

like image 314
Andre Vianna Avatar asked Sep 03 '25 04:09

Andre Vianna


1 Answers

How about IEquatable?

where TId : IEquatable<TId>
like image 105
Robert Jeppesen Avatar answered Sep 07 '25 10:09

Robert Jeppesen