jeudi 24 septembre 2020

Using reflection throws error in EF Core 3

We formerly used reflection to create linq queries, e.g. for the GetById method:

private IQueryable<T> GetQueryById(TKey id)
{
    var query = _dbset; //DbSet<T>

    var keyNames = _context.Model
            .FindRuntimeEntityType(typeof(T))
            .FindPrimaryKey()
            .Properties
            .Select(x => x.Name)
            .ToList();

    if (keyNames.Count() == 1)
    {
        query = query.Where(e => e.GetType().GetProperty(keyNames[0]).GetValue(e, null)
           .Equals(id)); //throws error
    }
        
    return query;
}

This does not seem to work any more in EF Core 3:

The LINQ expression 'DbSet .Where(c => c.GetType().GetProperty(__get_Item_0).GetValue( obj: c, index: null).Equals((object)__id_1))' could not be translated.

Is it possible to rewrite the query so that EF Core does not complain?





Aucun commentaire:

Enregistrer un commentaire