如何使用Fluent NHibernate映射CompositeId的引用

时间:2015-11-02 15:48:24

标签: c# nhibernate fluent-nhibernate fluent-nhibernate-mapping

我有三个课程ProductStockStockIdStock的复合ID为TokenInternalCode,这两个属性封装在新的类StockID中。

我的课程定义是:

public class Producto
{
    public virtual long Id { get; set;
    public virtual Stock Stock { get; set; }

    ... Some other (not so important ) properties ...

    public Producto()
    {
        ...
    }
}

public class Stock
{
    public virtual StockID ID { get; set; }
    public virtual Producto ProductoStock { get; set; }
    ... other properties ...
}

public class StockID
{
    public virtual string Token { get; set; }
    public virtual long CodigoInterno { get; set; }

    public override int GetHashCode()
    {
        int hash = GetType().GetHashCode();
        hash = (hash * 31) ^ CodigoInterno.GetHashCode();
        hash = (hash * 31) ^ Token.GetHashCode();

        return hash;
    }

    public override bool Equals(object obj)
    {
        var other = obj as StockID;

        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;

        return this.CodigoInterno == other.CodigoInterno &&
               this.Token == other.Token;
    }
}

这些是地图:

public class ProductoMap : ClassMap<Producto>
{
    public ProductoMap()
    {
        Id(x => x.Id);
        // ... Other Maps and References

        References<Stock>( p => p.Stock);
    }
}

public class StockMap : ClassMap<Stock>
{
    public StockMap()
    {
        CompositeId( stock => stock.ID)
            .KeyProperty(x => x.CodigoInterno)
            .KeyProperty(x => x.Token);

        // ... Other Maps and References
        References(x => x.ProductoStock);
    }
}

这是我得到的例外......

  

外键(FKD33BD86ADE26BE17:Producto [Stock_id]))必须与引用的主键具有相同的列数(Stock [CodigoInterno,Token])

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您必须将与您的类Producto匹配的属性与您的类Stock一起映射。它应该是这样的:

public class StockMap : ClassMap<Stock>
{
    public StockMap()
    {
        CompositeId( stock => stock.ID)
            .KeyProperty(x => x.CodigoInterno)
            .KeyProperty(x => x.Token);
        // ... Other Maps and References
        //This is ok since you have (i believe) a column in
        //in your table that stores the id from Producto
        References(x => x.ProductoStock).Column("idProducto");
        //Maybe you have to put the name of the column with
        //the id of Producto in your table Stock because
        //you could use it later.

    }
}

和ProductMap类:

public class ProductoMap : ClassMap<Producto>
{
    public ProductoMap()
    {
        Id(x => x.Id);
        // ... Other Maps and References
        //If you have the id from Stock in your Stock class
        //this will work.
        //References<Stock>( p => p.Stock);
        //If you don't have it, this will work:
        HasOne<Stock>(x => x.Stock).PropertyRef("Name of the column whit the product id in the Stock table");
    }
}

从我的观点来看,第二种选择似乎更好。无论如何,如果你有一个遗留数据库,那就不是一个很大的区别了。