我有一个要查询的多对多关系。我的问题与 Phillip Haydon在这里详述的问题非常相似,所以我将大量借用他的图表和解释。
Phillip 在 Jobs 和 Roles 之间有以下多对多关系(对不起,我还不能嵌入图像):
数据模式
Phillip 需要查询所有未分配给作业的角色。他的解决方案如下:
Role roleAlias = null;
var existing = QueryOver.Of<JobRole>()
.Where(x => x.Job.JobId == jobId)
.And(x => x.Role.RoleId != roleId)
.And(x => x.Role.RoleId == roleAlias.RoleId)
.Select(x => x.Role);
result = Session.QueryOver<Role>(() => roleAlias)
.Where(x => x.IsEnabled)
.WithSubquery.WhereNotExists(existing)
.OrderBy(x => x.Name).Asc
.List();
这非常有帮助,但是在此解决方案中似乎每个表都有一个实体;工作、工作角色和角色。JobRole 既有 Job 又有 Role。大概是这样的:
public class Job
{
public int JobId {get;set;}
public string Name {get; set;}
public bool IsEnabled {get;set;}
public bool IsDefault {get;set;}
}
public class Role
{
public int RoleId {get;set}
public string Name {get;set}
public bool IsEnabled {get;set}
public string RoleType {get;set}
}
public class JobRole
{
public Job Job {get;set}
public Role Role {get;set;}
}
这与我在建模多对多关系时看到的模式相冲突,特别是在清晰的架构示例和此处的建议中。在这些例子中,在我的例子中,我只有两个类,Job 和 Role。像这样的东西:
public class Job
{
public int JobId {get;set;}
public string Name {get; set;}
public bool IsEnabled {get;set;}
public bool IsDefault {get;set;}
public IList<Role> Roles {get;set;}
}
public class Role
{
public int RoleId {get;set}
public string Name {get;set}
public bool IsEnabled {get;set}
public string RoleType {get;set}
public List<Job> Jobs {get;set;}
}
就我而言,我需要找到所有只有角色的工作。我试过这样的东西
Job job = null;
Role role = null;
var jobs = Session.QueryOver(() => job)
.WithSubquery
.WhereExists(
QueryOver.Of(() => role)
.JoinAlias(() => role.Jobs, () => job))
.List().ToList();
但是 NHibernate 要求在 WhereExists 中选择的投影,如果没有提供,就会抱怨,这对我来说很有意义。
使用我的模型甚至可以使用 WhereExists 执行 QueryOver 子查询吗?
提前致谢。