NHibernate - 是否可以将列映射到集合复合对象

时间:2013-02-27 12:33:46

标签: nhibernate nhibernate-mapping fluent-nhibernate-mapping

使用NHibernate可以将表中的列映射到对象集合。

例如,如果我有一个设计非常糟糕的数据库表,其中包含以下列: 客户端ID 客户名称 First_AmountPaid Second_AmountPaid Third_AmountPaid Fourth_AmountPaid

是否可以将此映射到以下类结构,其中First_AmountPaid到Fourth_AmountPaid有自己的类实现?

public class Client
{
    public int ClientId { get; set; }
    public string ClientName { get; set; }

    public IList<AmountPaid> Amounts { get; set; }
}

public class AmountPaid
{
    public decimal Amount { get; set; }
}

public class FirstAmountPaid : AmountPaid{ }
public class SecondAmountPaid : AmountPaid{ }
public class ThirdAmountPaid : AmountPaid{ }
public class FourthAmountPaid : AmountPaid{ }

因此提供更有意义的代码结构。

谢谢

1 个答案:

答案 0 :(得分:0)

当listposition已经定义了金额的顺序时,我不确定为什么存在子类

Map(x => x.Amounts)
    .Columns.Add("First_AmountPaid", "Second_AmountPaid", "Third_AmountPaid", "Fourth_AmountPaid")
    .CustomType<AmountPaidType>();

class AmountPaid : IUserType
{
    public object Assemble(object cached, object owner)
    {
        return cached;
    }

    public object DeepCopy(object value)
    {
        return ((IList<AmountPaid>)x).Select(a => a.Clone()).ToList();
    }

    public object Disassemble(object value)
    {
        return value;
    }

    bool IUserType.Equals(object x, object y)
    {
        // assuming AmountPaid implements Equals
        return ((IList<AmountPaid>)x).SequenceEquals((IList<AmountPaid>)y);
    }

    public int GetHashCode(object x)
    {
        return x.GetHashCode();
    }

    public bool IsMutable
    {
        get { return true; }
    }

    public void NullSafeSet(cmd, value, index)
    {
        var list = (IList<AmountPaid>)value;
        NHibernateUtil.Double.NullSafeSet(cmd, list[0].Amount, index);
        NHibernateUtil.Double.NullSafeSet(cmd, list[1].Amount, index + 1);
        NHibernateUtil.Double.NullSafeSet(cmd, list[2].Amount, index + 2);
        NHibernateUtil.Double.NullSafeSet(cmd, list[3].Amount, index + 3);
    }

    public object NullSafeGet(rs, names, owner)
    {
        var list = new List<AmountPaid>();
        foreach (var name in names)
        {
            list.Add(new AmountPaid((double)NHibernateUtil.Double.Get(rs, name)));
        }
        return list;
    }

    public object Replace(object original, object target, object owner)
    {
        return original;
    }

    public Type ReturnedType
    {
        get { return typeof(IList<AmountPaid>); }
    }

    public SqlType[] SqlTypes
    {
        get { return new[] { SqlTypeFactory.Double, SqlTypeFactory.Double, SqlTypeFactory.Double, SqlTypeFactory.Double }; }
    }
}