![](/img/trans.png)
[英]Confusion using CompositeId / Composite Keys in Fluent NHibernate
[英]How to map a reference of a CompositeId using Fluent NHibernate
我有三个类Product
, Stock
, StockId
。 Stock
具有Token
和InternalCode
的复合ID,这两个属性封装在新的类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]))的列数必须与引用的主键(股票[CodigoInterno,令牌])相同
我怎样才能解决这个问题?
您必须将与类别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");
}
}
从我的角度来看,第二个选择似乎更好。 无论如何,如果您有一个旧数据库,那么这并不是什么大不了的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.