我一直在努力解决这个问题,但还无法找到解决方案。
我有以下情况(我已经削减了非必要部分):
public class Company : Base // Base has Guid Id
{
public virtual HeadQuarter HeadQuarter { get; set; }
}
public class HeadQuarter : Base
{
public virtual Company Company { get; set; }
}
映射:
public CompanyMap()
{
Id(x => x.Id).Column("CompanyId");
References(x => x.HeadQuarter)
.Column("HeadQuarterId")
.Unique()
.Cascade.All();
}
public HeadQuarterMap()
{
Id(x => x.Id)
.Column("HeadQuarterId");
HasOne(x => x.Company)
.PropertyRef(x => x.HeadQuarter)
.Cascade.All();
}
在我的数据库中生成两个表。我可以使用HeadQuarter插入公司。它工作正常。
问题在于,当我删除公司时,HeadQuarter不会被删除。这就是我使用级联的原因。
我怎样才能实现这一目标?
答案 0 :(得分:0)
我会说,映射应该反转。检查文档
在下面的示例中,我们将映射Car实体和SteeringWheel实体之间的关系。对于我们的业务规则,Car只会有一个SteeringWheel,所以我们会这样映射:
public class CarMap : ClassMap<Car>
{
public CarMap()
{
Table( "Vehicles.dbo.Car" );
Id( x => x.CarId );
Map( x => x.Name );
Map( x => x.Year );
HasOne( x => x.SteeringWheel ).PropertyRef( x => x.Car);
}
}
public class SteeringWheelMap : ClassMap<SteeringWheel>
{
public SteeringWheelMap()
{
Table( "Vehicles.dbo.SteeringWheel" );
Id( x => x.SteeringWheelId );
Map( x => x.Diameter );
Map( x => x.Color );
References( x => x.Car, "CarId" ).Unique();
}
}
所以,在我们的例子中,我们需要
public CompanyMap()
{
Id(x => x.Id).Column("CompanyId");
HasOne(x => x.HeadQuarter)
.PropertyRef(x => x.Company);
}
public HeadQuarterMap()
{
Id(x => x.Id)
.Column("HeadQuarterId");
References( x => x.Company, "CompanyId" ).Unique();
}