将对象列表作为组件映射到NHibernate中的不同表

时间:2014-08-12 14:29:56

标签: c# nhibernate

我和我的团队正在尝试使用NHibernate将旧数据库映射到更新的域模型(1)。在这个域模型中,我们有一个公共类用作两个不同类的组件(VehicleOwned和VehicleRented都有一个VehicleOrigins组件)。这两个类在数据库中都有自己的表,并将表中的字段映射到公共类。我们现在想要将一个集合添加到公共类(PreviousOwners)。由于数据库的结构,我们需要支持将其映射到两个不同的表(VehicleOwnedPreviousOwners和VehicleRentedPreviousOwners-table),但我们希望将其作为单个类公开并处理映射中的差异。我们将新的集合类(PreviousOwners)映射到属性的自己的映射文件中,并且可以在组件映射中设置表,因此一切正常。

我们面临的问题是表中的Id列在两个表之间的名称不同,并且没有明显的方法来声明映射中的id。 NHibernate有没有办法支持这种情况?

//the two classes that share a common component
class VehicleOwned
{
    public int VehicleOwnedId { get; set; }
    //...
    public VehicleOrigins Origins;
}

class VehicleRented
{
    public int VehicleRentedId { get; set; }
    //...
    public VehicleOrigins Origins;
}

//the component
class VehicleOrigins
{
    public string OriginalPaintJob { get; set; }
    //...
    public IList<PreviousOwner> PreviousOwners { get; set; }
}

//the class in the component that maps to two different tables
class PreviousOwner
{
    public int PreviousOwnerId { get; set; } //the column name for this id differs in both tables
    public string Name { get; set; } //the regular properties share the same column name across the tables
    //...
}

//the map for the class in the component
class PreviousOwnerMap : ClassMap<PreviousOwner>
{
    public PreviousOwnerMap()
    {
        //cannot map table here because it depends on the parent class
        //cannot map id here because it depends on the table which depends on the parent class
        Map(x => x.Name).Column("name");
    }
}

//the map for the classes, with a map to the component
class VehicleOwnedMap : ClassMap<VehicleOwned>
{
    public VehicleOwnedMap()
    {
        Table("VehicleOwned");
        Id(x => x.VehicleOwnedId).Column("VehicleOwnedId");
        Component(x => x.Origins, f => {
            f.Map(x => x.OriginalPaintJob).Column("OriginalPaintJob");
            f.HasMany(x => x.PreviousOwners)
                .Table("VehicleOwnedPreviousOwners");
                //can map the table, not the ID...
        });
    }
}

class VehicleRentedMap : ClassMap<VehicleRented>
{
    public VehicleRentedMap()
    {
        Table("VehicleRented");
        Id(x => x.VehicleRentedId).Column("VehicleRentedId");
        Component(x => x.Origins, f =>
        {
            f.Map(x => x.OriginalPaintJob).Column("OriginalPaintJob");
            f.HasMany(x => x.PreviousOwners)
                .Table("VehicleRentedPreviousOwners");
                //can map the table, not the ID...
        });
    }
}

(1)这是一个虚构的,故意简化的例子,用于解决这个问题。不,不幸的是,我们也无法更改模型OR数据库。

0 个答案:

没有答案