我想使用QueryOver编写NHibernate查询,该查询将一个实体连接到另一个具有“多对多”关系的实体,并且仅返回与我的where条件匹配的结果。抱歉,这有点令人困惑,但这也使我感到困惑。
public class SomeEntity{
public virtual int ID { get; set; }
public virtual string Name { get; set; }
public virtual Foo Foo { get; set; }
}
public class Foo{
public virtual int ID { get; set; }
public virtual IList<Bar> BarList { get; set; }
}
public class Bar{
public virtual int ID { get; set; }
public virtual IList<Foo> FooList { get; set; }
}
public class MapSomeEntity : ClassMap<SomeEntity>{
public MapSomeEntity(){
Id(x => x.ID).Column("id_some_entity");
Id(x => x.Name).Column("ds_name");
References(x => x.Foo, "id_foo_fk").Cascade.None();
}
}
public class MapFoo : ClassMap<Foo>{
public MapFoo(){
Id(x => x.ID).Column("id_foo");
HasManyToMany(x => x.BarList).Cascade.All().Table("foo_bar").ParentKeyColumn("id_foo_fk").ChildKeyColumn("id_bar_fk");
}
}
public class MapBar : ClassMap<Bar>{
public MapBar(){
Id(x => x.ID).Column("id_bar");
HasManyToMany(x => x.FooList).Cascade.All().Table("foo_bar").Inverse().ParentKeyColumn("id_bar_fk").ChildKeyColumn("id_foo_fk");
}
}
此查询:
SomeEntity e = null;
Foo foo = null;
Bar bar = null;
Session.QueryOver(() => e)
.Where(() => e.Name == "Something")
.JoinAlias(() => e.Foo , () => foo)
.JoinAlias(() => foo.BarList, () => bar)
.Where(() => bar.ID == 50)
.SelectList(list => list
.Select(() => e.ID)
.Select(() => e.Name));
这将生成此查询:
SELECT e.id_some_entity, e.ds_name FROM some_entity e
inner join foo f on e.id_foo_fk = f.id_foo
inner join foo_bar fb on f._id_foo = fb.id_foo_fk
inner join bar b on fb.id_bar_fk = b.id_bar WHERE b.id_bar = 50
但是此查询具有一些不必要的联接,我想要的是这样:
SELECT e.id_some_entity, e.ds_name FROM some_entity e
inner join foo_bar fb on e._id_foo_fk = fb.id_foo_fk
WHERE fb.id_bar_fk = 50
我尝试了很多事情,但是没有一个起作用,我不确定这是否可能,但是对此很高兴能给出答案