gpt4 book ai didi

c# - 使用泛型的 Entity Framework 相关对象

转载 作者:太空宇宙 更新时间:2023-11-03 15:44:57 24 4
gpt4 key购买 nike

在使用Linq to entities的时候有很多关于使用Include()和Load()获取相关表信息的问题。我对这个问题有不同的看法。

我的情况:

我有一个表,其中包含系统中每个用户的许多时间记录,并且我使用存储库模式和泛型进行开发,因此我的所有实体都有一个用于标准方法调用的接口(interface)。我关闭了延迟加载,我自己加载所有数据。因此,存储库中用于从具有相关表的表中加载所有记录的代码如下所示:

public class Repository<T> : IRepository<T> where T : class
{
protected readonly ApplicationDbContext Context;

public Repository(IConnectionHelper connection)
{
Context = connection.Context;
}
public virtual DbSet<T> ObjectSet
{
get { return Context.Set<T>(); }
}
public List<T> GetAll(String[] include, Expression<Func<T, bool>> predicate)
{
DbQuery<T> outQuery = null;
foreach (String s in include)
{
outQuery = ObjectSet.Include(s);
outQuery.Load();
}
return outQuery.Where(predicate).ToList();
}
}

方法的调用是这样的:

string[] includes = { "User.UserProfile", "CampaignTimeClocks.CampaignRole.Campaign", "Site", "Type" };
DateTime uTcCurrent = GetUtc();
DateTime MinClockinDate = uTcCurrent.AddHours(-10);
List<TimeClock> tcPending = _timeClock.GetAll(includes, x => (x.PendingReview || x.ClockInDate < MinClockinDate && x.ClockOutDate == null) && (x.Site.Id == currentUser.SiteId));

当此方法运行并加载第一个 User.Profile 表时,它会加载所有时钟记录并将它们与所有用户相关联,这需要一分钟以上的时间,这太长了,因为结束记录count 只有 185 条记录,但查询的初始负载运行 27,000 * 560 个用户,或 1500 万条记录,而且随着时间的推移,这只会变得更糟。

问题是我如何在没有这种负载开销的情况下做到这一点,我知道我可以链接包含,但由于包含的数量将根据调用的数据是什么以及我正在做什么而改变,我不能简单地对包含链进行硬编码。

我也试过:

List<TimeClock> testLst =  _timeClock.GetAll(x => x.PendingReview || 
(x.ClockInDate < MinClockinDate && x.ClockOutDate == null))
.Select(x => new TimeClock{Id = x.Id,
ClockInDate = x.ClockInDate,
ClockOutDate = x.ClockOutDate,
TotalClockTime = x.TotalClockTime,
Notes = x.Notes,
PendingReview = x.PendingReview,
Type = x.Type,
User = x.User,
CampaignTimeClocks = x.CampaignTimeClocks,
TimeClockAdjustments = x.TimeClockAdjustments,
Site = x.User.Site}).ToList();

这将为我提供 User.Profile 信息,但 Site 和 Type 属性为空。

所以我有点不知道如何在这里加载我需要的数据。

非常感谢所有帮助。

最佳答案

能不能先拿到初始列表

List<TimeClock> testLst =  _timeClock.Where(x => x.PendingReview || (x.ClockInDate < MinClockinDate && x.ClockOutDate == null)).ToList();

然后调用以 T 作为参数的修改后的 GetAll()

关于c# - 使用泛型的 Entity Framework 相关对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28481018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com