多对多 EF6 查询...试图获取属于实体 A 并包含所有实体 A 的实体 B

Many-to-Many EF6 query ... trying to get entity Bs that belong to entity A and include all entity As

我的模型……(仅供参考,“申请”在工作申请中,“管理员”在被指派负责此申请的人员中)

public class Application
{
  public int Id { get; set; }
  public string Title { get; set; }

  public ICollection<Administrator> Administrators { get; set; }
}

public class Administrator
{
  public int Id { get; set; }
  public string Username { get; set; }

  public ICollection<Application> Applications { get; set; }
}

注意应用程序和管理员之间的多对多关系。

它是一个 Intranet 应用程序,用户(也将是一个或多个应用程序的管理员)将使用 windows 身份验证来识别。我想 return JSON,只针对用户是管理员的应用程序,但也包括这些应用程序的所有管理员。例如,John 创建了一个名为“Nurse Practitioner for Pediatric Clinic”的新应用程序,这使 John 自动成为该应用程序的管理员,但 John 也将 Betty 指定为该应用程序的管理员。Betty 不是任何其他应用程序的管理员。如果 Betty 登录在中,她应该获得名为“儿科诊所的执业护士”的应用程序对象和该应用程序的 2 位管理员(John 和 Betty)。

这有效,但包括所有应用程序,不限于 Betty 的...

context.Applications.Include("Administrators").ToList();

这些工作但显然不是我想要的...

context.Administrators.Include("Applications").ToList();
context.Applications.Include("Administrators").Where(a => a.Id.Equals(1)).ToList();
context.Administrators.ToList();
context.Administrators.Find(1);

这行不通……

context.Applications.Include("Administrators").Where(a => a.Administrators.Contains(context.Administrators.First())).ToList();

获取...

An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: The method 'First' can only be used as a final query operation. Consider using the method 'FirstOrDefault' in this instance instead.

这行不通……

context.Administrators.Find(1).Applications.ToList();

获取...

An exception of type 'System.ArgumentNullException' occurred in System.Core.dll but was not handled in user code
Additional information: Value cannot be null.

虽然我知道 Id=1 的管理员有 2 个应用程序。

这有效……

(from app in context.Applications
                         from admin in app.Administrators
                         where admin.Username == “John"
                         select app).ToList();

但它不包括管理员,如果我像这样添加一个 Include() 子句……

(from app in context.Applications
                         from admin in app.Administrators
                         where admin.Username == “John"
                         select app).Include(“Administrators”).ToList();

没用。

想不通。任何帮助将非常感激。谢谢。

自己想出来了...

// get the current user's id
var userId = 1;
var apps = (from Application app in context.Applications.Include("Administrators")
                        where app.Administrators.Select(a => a.Id).Contains(userId)
                        select app).ToList();