我对EF Core很陌生。我总是使用EF 6.0,从来没有使用过包含。现在问题出现了我应该如何使用这些包括。我想出了三个可能的选择,想知道你更喜欢使用/哪个是最快的?为什么?
在这些样本中,我的目的是获取俱乐部的详细信息。我想检查是否存在具有相应身份证的俱乐部,然后获取所有信息。
选项1:
using (var context = new TrainingSchedulerContext())
{
var clubs = context.Clubs.Where(c => c.Id == clubId);
if (clubs.Count() == 0)
return NotFound();
var club = clubs.Include(c => c.Memberships)
.Include(c => c.MembershipRequests)
.Include(c => c.TrainingTimes)
.Include(c => c.AdminRoles)
.SingleOrDefault();
}
选项2:
using (var context = new TrainingSchedulerContext())
{
var club = context.Clubs.Include(c => c.Memberships)
.Include(c => c.MembershipRequests)
.Include(c => c.TrainingTimes)
.Include(c => c.AdminRoles)
.SingleOrDefault(c => c.Id == clubId);
if (club == null)
return NotFound();
}
选项3:
using (var context = new TrainingSchedulerContext())
{
var club = context.Clubs.SingleOrDefault(c => c.Id == clubId);
if (club == null)
return NotFound();
club = context.Clubs.Include(c => c.Memberships)
.Include(c => c.MembershipRequests)
.Include(c => c.TrainingTimes)
.Include(c => c.AdminRoles)
.SingleOrDefault(c => c.Id == clubId);
}
答案 0 :(得分:2)
让我们从最坏到最好:
Count
,另一次针对SingleOrDefault
。第一个是不需要的,因此: