在Fluent NHibernate中映射复合键

我是stream利的NHibernate新手。 现在我面临着复合键映射的一个问题。 任何人都可以指出URL或样品吗?

有一个CompositeId方法。

 public class EntityMap : ClassMap<Entity> { public EntityMap() { CompositeId() .KeyProperty(x => x.Something) .KeyReference(x => x.SomethingElse); } } 

如果这是你的第一堂课

 public class EntityMap : ClassMap<Entity> { public EntityMap() { UseCompositeId() .WithKeyProperty(x => x.Something) .WithReferenceProperty(x => x.SomethingElse); } } 

这里是第二个关于实体的参考

 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(); } } 

另外需要注意的是,您必须为使用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 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