使用Fluent Nhibernate自动映射的多对多关系
我们面临着使用fluent nhibernate自动映射应用多对多关系的问题 域模型的简化形式如下:使用Fluent Nhibernate自动映射的多对多关系,nhibernate,fluent-nhibernate,many-to-many,automapping,Nhibernate,Fluent Nhibernate,Many To Many,Automapping,我们面临着使用fluent nhibernate自动映射应用多对多关系的问题 域模型的简化形式如下: public class Group { private readonly IList<Recipient> _recipients = new List<Recipient>(); public virtual IList<Recipient> Recipients { get { return _recipients
public class Group
{
private readonly IList<Recipient> _recipients = new List<Recipient>();
public virtual IList<Recipient> Recipients
{
get { return _recipients; }
}
}
public class Recipient
{
private readonly IList<Group> _groups = new List<Group>();
public virtual IList<Group> Groups
{
get { return _ groups; }
}
}
公共类组
{
私有只读IList_recipients=新列表();
公共虚拟IList收件人
{
获取{return\u recipients;}
}
}
公共类收件人
{
私有只读IList_groups=新列表();
公共虚拟IList组
{
获取{return}groups;}
}
}
正如上面的代码所描述的,组和收件人具有多对多关系。
我们正在使用fluent nhibernate的自动映射功能将我们的领域模型映射到数据库。所以,我们需要使用约定进行自动映射。
以下是我们用于多对多约定的代码:-
public class ManyToManyConvention : IHasManyToManyConvention
{
#region IConvention<IManyToManyCollectionInspector,IManyToManyCollectionInstance> Members
public void Apply(FluentNHibernate.Conventions.Instances.IManyToManyCollectionInstance instance)
{
if (instance.OtherSide == null)
{
instance.Table(
string.Format(
"{0}To{1}",
instance.EntityType.Name + "_Id",
instance.ChildType.Name + "_Id"));
}
else
{
instance.Inverse();
}
instance.Cascade.All();
}
#endregion
}
公共类多人约定:IHasManyToManyConvention
{
#地区I会议成员
public void Apply(FluentNHibernate.Conventions.Instances.imanytomanycollectionstance实例)
{
if(instance.OtherSide==null)
{
实例.表(
字符串格式(
“{0}到{1}”,
instance.EntityType.Name+“\u Id”,
instance.ChildType.Name+“_Id”);
}
其他的
{
instance.Inverse();
}
Cascade.All();
}
#端区
}
我在这里找到了这个解决方案:
但在上面的代码中,在调试Recipients->Groups和Groups->Recipients实例的时间时,OtherSide不为null。假设是第一次实例。另一边将不为null,第二次它将为null,因为关系应用于一边,所以我们将只对其应用相反的结果。
所以它创建了两个相同的映射表。
将具有相同模式的两个表加载到数据库是非常困难的。甚至当我尝试使用多对多关系将域模型保存到数据库时。它只保存了一面,即它将收件人保存在组中,但不将组保存在收件人中。在数据库中,它只在一个映射表中有条目,而不是在两个映射表中都有条目
所以,问题是我们做的是对的吗?如果没有,那么怎么做。您可以将反转本身作为标准
public void Apply(IManyToManyCollectionInstance instance)
{
Debug.Assert(instance.OtherSide != null);
// Hack: the cast is nessesary because the compiler tries to take the Method and not the property
if (((IManyToManyCollectionInspector)instance.OtherSide).Inverse)
{
instance.Table(
string.Format(
"{0}To{1}",
instance.EntityType.Name + "_Id",
instance.ChildType.Name + "_Id"));
}
else
{
instance.Inverse();
}
instance.Cascade.All();
}
您使用哪个版本的FNH?如果(instance.OtherSide==null | | |((imanytomanycollectionspector)instance.OtherSide).Inverse)@dario-g请参见断言
instance.OtherSide==null
在else中需要一些额外的考虑