gpt4 book ai didi

NHibernate/FluentNHibernate 属性包

转载 作者:行者123 更新时间:2023-12-03 11:23:36 28 4
gpt4 key购买 nike

给定一个 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 "Unexpected row count: 0; expected: 1"(我也不想在 VehicleProperty 上拥有 Vehicle 属性)...
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 = ''

最佳答案

我完全同意 Stefan 的观点,虽然我不能证明他映射的正确性,但直接翻译成 Fluent NHibernate 如下:

public class VehicleMap : ClassMap<Vehicle>
{
public VehicleMap()
{
Id(x => x.Id);
Map(x => x.Registration);

HasMany(x => x.Properties)
.Component(c =>
{
c.Map(x => x.Name);
c.Map(x => x.Value);
})
.Cascade.AllDeleteOrphan();
}
}

关于NHibernate/FluentNHibernate 属性包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/814931/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com