「Fluent NHibernate/フルーエントマッピング/複合主キー」の版間の差分
ナビゲーションに移動
検索に移動
imported>Administrator |
imported>Administrator (→マッピング) |
||
45行目: | 45行目: | ||
{ | { | ||
CompositeId() | CompositeId() | ||
− | .KeyProperty(x => x.Id1 | + | .KeyProperty(x => x.Id1) |
− | .KeyProperty(x => x.Id2 | + | .KeyProperty(x => x.Id2) |
; | ; | ||
} | } |
2012年7月8日 (日) 08:38時点における最新版
Fluent NHibernateで複合主キーを記述する方法。
エンティティ[編集 | ソースを編集]
複合主キーを用いるエンティティクラスでは、とくに何もしてなくてもEqualsメソッドとGetHashCodeメソッドをオーバーライドしておく必要がある。これをしないと実行時にエラーとなる。
public class NodeX
{
public virtual long Id1 { get; set; }
public virtual long Id2 { get; set; }
// これ重要
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
var cmp = obj as NodeX;
if (cmp == null)
{
return false;
}
if (Id1 != cmp.Id1 || Id2 != cmp.Id2)
{
return false;
}
return true;
}
// これも重要
public override int GetHashCode()
{
return (Id1 + "|" + Id2).GetHashCode();
}
}
マッピング[編集 | ソースを編集]
マッピングクラスではCompositeIdメソッドでマッピングを行う。 KeyPropertyメソッドで複合主キーにしたいカラムを次々と書いてくことで実現できる。
public class NodeXMap : ClassMap<NodeX>
{
public NodeXMap()
{
CompositeId()
.KeyProperty(x => x.Id1)
.KeyProperty(x => x.Id2)
;
}
}
関連項目[編集 | ソースを編集]
参考文献[編集 | ソースを編集]