给定一个 Vehicle 类和一个 VehicleProperty 类...
public class Vehicle
{
public virtual int Id { get; protected set; }
public virtual string Registration { get; set; }
private List<VehicleProperty> _properties = new List<VehicleProperty>();
public virtual IEnumerable<VehicleProperty> Properties
{
get { return _properties; }
protected set{ _properties = new List<VehicleProperty>(value);}
}
public virtual void AddProperty(string name, string value)
{
_properties.Add(new VehicleProperty {Name = name, Value = value});
}
}
public class VehicleProperty
{
public virtual string Name { get; set; }
public virtual string Value { get; set; }
}
如何映射这两个类,以便 VehicleProperty 表具有 [VehicleId] 和 [Name] 的复合键。 Vehicle 将是一个聚合根(VehicleProperty 不能在 Vehicle 类之外访问)。
我已经尝试了我能想到的一切(我是 NHibernate 的新手,所以这并不多)
public class VehicleMap : ClassMap<Vehicle>
{
public VehicleMap()
{
Id(x => x.Id);
Map(x => x.Registration);
HasMany(x => x.Properties)
.Inverse()
.Cascade.All();
}
}
public class VehiclePropertyMap : ClassMap<VehicleProperty>
{
public VehiclePropertyMap()
{
UseCompositeId()
.WithKeyProperty(x => x.Name)
.WithKeyReference(x => x.Vehicle, "Vehicle_Id");
Map(x => x.Name);
Map(x => x.Value);
}
}
此映射会产生以下 sql 和 StaleStateException“意外行数:0;预期:1”(我也不想在 VehicleProperty 上拥有车辆属性)...
INSERT INTO "Vehicle" (Registration) VALUES (@p0); select last_insert_rowid(); @p0 = 'AA09CDE'
UPDATE "VehicleProperty" SET Name = @p0, Value = @p1 WHERE Name = @p2 AND Vehicle_Id = @p3; @p0 = 'Colour', @p1 = 'Black', @p2 = 'Colour', @p3 = ''