Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query EntityFramework using generic property type?

When I call DbSet.FirstOrDefault() by passing a predicate that compares generic type TId, I get the following exception:

unable to create a constant value of type 'system.object'. only primitive types or enumeration types are supported in this context.

Interface for type being queried:

interface IEntity<TId>
{
    TId id { get; set; }
}

The exception is thrown here:

public virtual TEntity Get<TEntity, TId>(TId id) where TEntity : class, IEntity<TId>
{
    return dbContext.Set<TEntity>().FirstOrDefault(e => e.Id.Equals(id));
}

The function will only work if TId is constrained as struct. How can I include string as supported type? If it's not possible, is it possible to accomplish the task a different way?

like image 309
user845279 Avatar asked Dec 05 '25 05:12

user845279


2 Answers

This will work for strings too:

public virtual TEntity Get<TEntity, TId>(TId id) 
    where TEntity : class, IEntity<TId>
    where TId: IEquatable<TId>
{
    return dbContext.Set<TEntity>().FirstOrDefault(e => e.Id.Equals(id));
}
like image 89
UserControl Avatar answered Dec 07 '25 18:12

UserControl


You can simply use Find method:

public virtual TEntity Get<TEntity, TId>(TId id) where TEntity : class, IEntity<TId>
{
    return dbContext.Set<TEntity>().Find(id);
}
like image 30
Slava Utesinov Avatar answered Dec 07 '25 18:12

Slava Utesinov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!