私はFluentNHibernateを初めて使用し、複合キーをマップする方法を理解できませんでした。
これどうやってするの?どのようなアプローチを取る必要がありますか?
私はFluentNHibernateを初めて使用し、複合キーをマップする方法を理解できませんでした。
これどうやってするの?どのようなアプローチを取る必要がありますか?
方法がありCompositeId
ます。
public class EntityMap : ClassMap<Entity>
{
public EntityMap()
{
CompositeId()
.KeyProperty(x => x.Something)
.KeyReference(x => x.SomethingElse);
}
}
もう 1 つの注意点は、CompositeId を使用して、エンティティの Equals メソッドと GetHashCode メソッドをオーバーライドする必要があることです。受け入れられた回答マッピング ファイルを指定すると、エンティティは次のようになります。
public class Entity
{
public virtual int Something {get; set;}
public virtual AnotherEntity SomethingElse {get; set;}
public override bool Equals(object obj)
{
var other = obj as Entity;
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return other.SomethingElse == SomethingElse && other.Something == Something;
}
public override int GetHashCode()
{
unchecked
{
return (SomethingElse.GetHashCode()*397) ^ Something;
}
}
}
これがあなたの最初のクラスなら
public class EntityMap : ClassMap<Entity>
{
public EntityMap()
{
UseCompositeId()
.WithKeyProperty(x => x.Something)
.WithReferenceProperty(x => x.SomethingElse);
}
}
これはエンティティに関する参照を持つ2番目のものです
public class SecondEntityMap : ClassMap<SecondEntity>
{
public SecondEntityMap()
{
Id(x => x.Id);
....
References<Entity>(x => x.EntityProperty)
.WithColumns("Something", "SomethingElse")
.LazyLoad()
.Cascade.None()
.NotFound.Ignore()
.FetchType.Join();
}
}
複合識別子を持つエンティティ、つまり複合主キーを持つテーブルにマップされ、多くの列で構成されるエンティティが必要になる場合があります。この主キーを構成する列は、通常、別のテーブルへの外部キーです。
public class UserMap : ClassMap<User>
{
public UserMap()
{
Table("User");
Id(x => x.Id).Column("ID");
CompositeId()
.KeyProperty(x => x.Id, "ID")
.KeyReference(x => x.User, "USER_ID");
Map(x => x.Name).Column("NAME");
References(x => x.Company).Column("COMPANY_ID").ForeignKey("ID");
}
}
詳細については、http: //www.codeproject.com/Tips/419780/NHibernate-mappings-for-Composite-Keys-with-associを参照してください。