Repository generic method GetById using eager loading

后端 未结 3 585
傲寒
傲寒 2021-01-23 22:33

I am using Entity Framework and would like to create generic GetById method in Repository class with eager loading:

Here is my method which uses lazy-lo

3条回答
  •  囚心锁ツ
    2021-01-23 22:56

    This is the update for Entity Framework Core 2.0. Also this method using the new metadata properties with EF to automatically get the first level navigation properties.

    public virtual T Get(object id)
    {
            var propertyName = "AddressId";
    
            //get all navigation properties defined for entity
            var navigationProps = _context.Model.FindEntityType(typeof(T)).GetNavigations();
    
            //turn those navigation properties into a string array
            var includeProperties = navigationProps.Select(p => p.PropertyInfo.Name).ToArray();
    
            //make parameter of type T
            var parameter = Expression.Parameter(typeof(T), "e");
    
            //create the lambda expression
            var predicateLeft = Expression.PropertyOrField(parameter, propertyName);
            var predicateRight = Expression.Constant(id);
            var predicate = Expression.Lambda>(Expression.Equal(predicateLeft, predicateRight), parameter);
    
            //get queryable
            var query = _context.Set().AsQueryable();
    
            //apply Include method to the query multiple times
            query = includeProperties.Aggregate(query, Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.Include);
    
            //return first item in query
            return query.FirstOrDefault(predicate);
    }
    

提交回复
热议问题