通用存储库,函数解释/ c#
本文关键字:解释 函数 存储 | 更新日期: 2023-09-27 18:10:31
我发现了一些有趣的通用存储库,但我无法弄清楚函数的作用:performanmincludes (includeProperties, query);
调用performanminclations,
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;
}
}
PerformInclusions
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), "");
所以我有2个问题,函数performinclations()做什么,有人能给我一个例子,includeproperties会在调用single()函数。
Thanks in advance
正如@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
为null的实体
_repo.Single(t => t.Id == 1, "Thing");
OR _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