我想写下面的代码更抽象。
private void LoadRelatedData(TabAccount tabAccount)
{
if (ConxCore.Instance.EntityModel.Entry(tabAccount).Collection(x => x.TabAccountLangs).IsLoaded == false)
{
var list = (from x in ConxCore.Instance.EntityModel.TabAccounts
from y in x.TabAccountLangs
select y).ToList();
}
}
我想要摘要的部分如下:
.Entry(tabAccount) - >应该采取每个EntitySet
x => x.TabAccountLangs - >应该在调用Method时指定我指定的属性(可能会抛出MemberExpression)
... TabAccounts - >应该从EntitySet加载DbSet我用
来自y的x.TabAccountLangs - >应该是上面的财产
关于抽象,我只是想避免一遍又一遍地复制/粘贴这些代码,只是更改上面提到的4个点,很高兴能够用给定的参数调用这个方法,然后方法完成其余的工作。
所以而不是:
private void LoadRelatedData(TabAccount tabAccount)
{
if (ConxCore.Instance.EntityModel.Entry(tabAccount).Collection(x => x.TabAccountLangs).IsLoaded == false)
{
var list = (from x in ConxCore.Instance.EntityModel.TabAccounts
from y in x.TabAccountLangs
select y).ToList();
}
}
private void LoadRelatedData(TabElement tabElement)
{
if (ConxCore.Instance.EntityModel.Entry(tabElement).Collection(x => x.TabElementLangs).IsLoaded == false)
{
var list = (from x in ConxCore.Instance.EntityModel.TabElements
from y in x.TabElementLangs
select y).ToList();
}
}
像这样(只有伪代码):
private void LoadRelatedData(object obj, object collection, object dbSetOfObj)
{
if (ConxCore.Instance.EntityModel.Entry(obj).Collection(x => x.collection).IsLoaded == false)
{
var list = (from x in ConxCore.Instance.EntityModel.dbSetOfObj
from y in x.collection
select y).ToList();
}
}
并调用此方法:
LoadRelatedData(tabAccount, TabAccountLangs, TabAccounts);
LoadRelatedData(tabElement, TabElementLangs, TabElements);
希望你能帮助我。提前谢谢。
答案 0 :(得分:2)
using System.Data.Entity; // For the Include extension method.
private void LoadRelatedData<TEntity, TRelated>(TEntity entity, Expression<Func<TEntity, ICollection<TRelated>> navigationProperty)
where TEntity : class
where TRelated : class
{
if (!ConxCore.Instance.EntityModel.Entry(entity).Collection(navigationProperty).IsLoaded)
{
var list = ConxCore.Instance.EntityModel.Set<TEntity>().Include(navigationProperty).ToList();
}
}
然后,您可以通过以下方式调用它:
LoadRelatedData(tabAccount, ta => ta.TabAccountLangs);
LoadRelatedData(tabElement, te => te.TabElementLangs);
但是,您知道这样的调用会加载任何x的所有相关数据吗?也就是说,您可能以非特别优化的方式加载大量数据。如果您只想加载单个实体的相关数据,可以从Collection
调用返回的对象加载集合:
private void LoadRelatedDataOfSingleObject<TEntity, TRelated>(TEntity entity, Expression<Func<TEntity, ICollection<TRelated>> navigationProperty)
where TEntity : class
where TRelated : class
{
var collectionEntry = ConxCore.Instance.EntityModel.Entry(entity).Collection(navigationProperty);
if (!collectionEntry.IsLoaded) collectionEntry.Load();
}
但是,如果要加载许多对象的数据,则应考虑使用Include
extension methods之一。