存储库通用方法GetById使用热切加载 [英] Repository generic method GetById using eager loading
问题描述
我正在使用Entity Framework,并希望在Repository类中使用eager加载创建通用的 GetById 方法:
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-loading:
public virtual TEntity GetById(object id)
{
return DbSet.Find(id);
}
我知道方法查找不支持急切加载,但是如何可以修改此方法来使用热心加载,以便我使用以下方法(例如):
I know method Find does not support eager loading, but how it is possible to modify this method to use eager loading, so that I use this method as follows(for an example):
_unitOfWork.MyRepository.GetById(includeProperties: "Users");
推荐答案
一种可能的方法是使用 FirstOrDefault
与谓语超过 DbSet
与 Include
s。使用 <$ c手动构建谓词不难$ c> Expression.Equal 方法,但主要的挑战是如何获取关键属性名称。幸运的是,我们可以使用一些 ObjectContext
方法来做到这一点,所以实现可能是这样的(假设我们可以访问具体的 DbContext
instance):
One possible way is to use FirstOrDefault
with predicate over the DbSet
with Include
s. It's not hard to build manually a predicate using Expression.Equal
method, but the main challenge is how to get the key property name. Luckily we can use some ObjectContext
methods to do that, so the implementation could be like this (assuming we have access to the concrete DbContext
instance):
public virtual TEntity GetById(object id, params string[] includeProperties)
{
var propertyName = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)DbContext).ObjectContext
.CreateObjectSet<TEntity>().EntitySet.ElementType.KeyMembers.Single().Name;
var parameter = Expression.Parameter(typeof(TEntity), "e");
var predicate = Expression.Lambda<Func<TEntity, bool>>(
Expression.Equal(
Expression.PropertyOrField(parameter, propertyName),
Expression.Constant(id)),
parameter);
var query = DbSet.AsQueryable();
if (includeProperties != null && includeProperties.Length > 0)
query = includeProperties.Aggregate(query, System.Data.Entity.QueryableExtensions.Include);
return query.FirstOrDefault(predicate);
}
这篇关于存储库通用方法GetById使用热切加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!