我有一个与a具有一对多关系的Vessel对象 VesselDetail对象。当我将VesselDetail对象添加到Vessel对象并尝试保存Vessel对象时,似乎NHibernate在插入VesselDetail对象时不添加外键。
我在哪里错了?我只是想不出来。
错误讯息: BDN.FindVessel.Tests.Integration.NhibernateRepositoryTests.SaveVessel_ShouldAddDetailsToDb_WhenAddedToEntity: NHibernate.Exceptions.GenericADOException:无法插入:[BDN.FindVessel.Domain.VesselDetail] [SQL:INSERT INTO BoatsDetails(SaftyGear,OtherMachineryAndGear,Material,Size,Various,TranslatorId,SpeenAndConsumption,MainMachinery,Created,Class,Capasities,Culture,内部,电子,DeckGear)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);选择SCOPE_IDENTITY()] ----> System.Data.SqlClient.SqlException:无法将值NULL插入列'BoatId',表'FindVesselTest.dbo.BoatsDetails';列不允许空值。 INSERT失败。 声明已经终止。
public class Vessel
{
public virtual int BoatId { get; set; }
public virtual IList<VesselDetail> Details { get; set; }
//...
}
public class VesselDetail
{
public virtual int VesselDetailId { get; set; }
//some other properties
//..
}
public class VesselMap: ClassMap<Vessel>
{
public VesselMap()
{
WithTable("Boats");
Id(x => x.BoatId, "Id");
//..
HasMany(x => x.Details)
.WithKeyColumn("BoatId") //foreign key in the BoatsDetails table
.Cascade.All();
}
}
public class VesselDetailMap:ClassMap<VesselDetail>
{
public VesselDetailMap()
{
WithTable("BoatsDetails");
Id(x => x.VesselDetailId, "Id");
//...
}
}
答案 0 :(得分:10)
我似乎缺少一些基本的NHibernate技能。稍微阅读一下,似乎你需要让子对象负责一对多的关系。
这解决了我的问题:
public class VesselMap: ClassMap<Vessel>
{
public VesselMap()
{
//...
HasMany(x => x.Details)
.Inverse()
.WithKeyColumn("BoatId");
}
}
public class VesselDetailMap:ClassMap<VesselDetail>
{
public VesselDetailMap()
{
//..
References(x => x.Vessel, "BoatId")
.Cascade
.SaveUpdate();
}
}