我找到了一些有趣的通用存储库,但我无法弄清楚该函数的作用:PerformInclusions(includeProperties,query);
public T Single(Expression<Func<T, bool>> where, string includeProperties)
{
try
{
IQueryable<T> query = IDbSet;
query = PerformInclusions(includeProperties, query);
return query.Single(where);
}
catch (InvalidOperationException ex)
{
return null;
}
}
private static IQueryable<T> PerformInclusions(string includeProperties,
IQueryable<T> query)
{
if (includeProperties != null && includeProperties.Length > 0)
{
foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
}
return query;
}
我可以使用没有第二个参数的单个函数。
Euser test = Adapter.EuserRepository.Single(u => u.EuserEmail.Equals(user.EuserEmail), "");
所以我有两个问题,函数PerformInclusions()做了什么,有人可以举例说明include()函数调用中的includeproperties。
提前致谢
答案 0 :(得分:2)
正如@Andrei所说,这允许您使用熟悉的EF include语法来急切加载导航属性。 nav属性渴望加载的另一种选择是通过lambdas,如下所示:
public T GetBy(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includes)
{
var result = GetAll();
if (includes.Any())
{
foreach (var include in includes)
{
result = result.Include(include);
}
}
return result.FirstOrDefault(predicate);
}
如果您的实体具有如下导航属性:
public class Test{
public int Id {get;set;}
public SomethingElse Thing {get;set;}
}
_repo.Single(t => t.Id == 1, "");
或_repo.GetBy(t => t.Id == 1);
将返回Thing
为空的实体
_repo.Single(t => t.Id == 1, "Thing");
或_repo.GetBy(t => t.Id == 1, t=>t.Thing);
将返回通过外键填充Thing的实体
有关EF中导航属性的详细信息,请查看我的博客http://blog.staticvoid.co.nz/2012/7/17/entity_framework-navigation_property_basics_with_code_first