我正在尝试使用 JoinAlias 加入多个实体,但不知道如何让多个实体加入。以下代码导致 SQL 错误:
[TestMethod]
public void TestAliases()
{
App_Start.NHibernateProfilerBootstrapper.PreStart();
var type = new ShirtStyleType {Id = 1};
var style = new ShirtStyle {Id = 1, ShirtStyleType = type};
var shirt = new Shirt {Id = 1};
var shirtStyle = new ShirtShirtStyle {Shirt = shirt, ShirtStyle = style};
shirt.ShirtStyles = new[] {shirtStyle};
using (Session.BeginTransaction())
Session.Save(shirt);
Session.Clear();
using (Session.BeginTransaction())
{
Shirt shirtAlias = null;
ShirtShirtStyle shirtStylesAlias = null;
ShirtStyle shirtStyleAlias = null;
ShirtStyleType shirtStyleTypeAlias = null;
var query = Session.QueryOver<Shirt>(() => shirtAlias)
.JoinAlias(() => shirtAlias.ShirtStyles, () => shirtStylesAlias)
.JoinAlias(() => shirtStylesAlias.ShirtStyle, () => shirtStyleAlias)
.JoinAlias(() => shirtStyleAlias.ShirtStyleType, () => shirtStyleTypeAlias)
.Where(() => shirtStyleTypeAlias.Id == 1)
.List();
}
}
错误:
ERROR:
SQLite error
no such column: shirtstyle3_.Id
导致错误的 SQL:
SELECT this_.Id as Id0_1_,
shirtstyle1_.Shirt as Shirt1_0_,
shirtstyle1_.ShirtStyle as ShirtStyle1_0_
FROM "Shirt" this_
inner join "ShirtShirtStyle" shirtstyle1_
on this_.Id = shirtstyle1_.Shirt_id
WHERE shirtstyle3_.Id = 1 /* @p0 */
很明显可以看出为什么会发生错误 - 查询缺少连接,特别是“衬衫衬衫样式”以外的每个连接。根据我对 JoinAlias 的理解,我提供的代码应该是加入必要的表,但事实并非如此,我也不明白为什么。在这种情况下,我还需要让 JoinAlias 工作吗?
我为此测试创建的实体和映射如下,以防它与它们的映射方式有关。
实体:
public class Shirt
{
public virtual int Id { get; set; }
public virtual IList<ShirtShirtStyle> ShirtStyles { get; set; }
}
public class ShirtShirtStyle
{
public virtual Shirt Shirt { get; set; }
public virtual ShirtStyle ShirtStyle { get; set; }
protected bool Equals(ShirtShirtStyle other)
{
return Equals(Shirt, other.Shirt) && Equals(ShirtStyle, other.ShirtStyle);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((ShirtShirtStyle) obj);
}
public override int GetHashCode()
{
unchecked
{
return ((Shirt != null ? Shirt.GetHashCode() : 0)*397) ^ (ShirtStyle != null ? ShirtStyle.GetHashCode() : 0);
}
}
}
public class ShirtStyle
{
public virtual int Id { get; set; }
public virtual ShirtStyleType ShirtStyleType { get; set; }
}
public class ShirtStyleType
{
public virtual int Id { get; set; }
}
地图:
public class ShirtMap : ClassMap<Shirt>
{
public ShirtMap()
{
Id(x => x.Id).GeneratedBy.Assigned();
HasMany(x => x.ShirtStyles);
}
}
public sealed class ShirtShirtStyleMap : ClassMap<ShirtShirtStyle>
{
public ShirtShirtStyleMap()
{
CompositeId()
.KeyReference(x => x.Shirt)
.KeyReference(x => x.ShirtStyle);
}
}
public sealed class ShirtStyleMap : ClassMap<ShirtStyle>
{
public ShirtStyleMap()
{
Id(x => x.Id).GeneratedBy.Assigned();
References(x => x.ShirtStyleType);
}
}
public sealed class ShirtStyleTypeMap : ClassMap<ShirtStyleType>
{
public ShirtStyleTypeMap()
{
Id(x => x.Id).GeneratedBy.Assigned();
}
}