2009-01-15 130 views
38

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

+0

可以在这里 http://devlicio.us/blogs/derik_whittaker/archive/2009/01/16/using-fluentnhibernate-to-map-composite-keys-for-a-table找到更详细的例子.aspx – 2009-01-28 19:44:57

回答

48

有一个CompositeId方法。

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

请注意,在NHibernate的新版本中,UseCompositeId替换为CompositeId,而WithKeyProperty只是KeyProperty – 2010-10-28 17:20:01

+2

@Rob Walker:同时WithReferenceProperty已成为KeyReference – Mulki 2011-02-18 07:48:55

5

,如果这是你的第一类

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

     } 
    } 
1

可能有必要与复合标识,映射实体的实体到具有由许多列组成的复合主键的表。组成这个主键的列通常是另一个表的外键。

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

2

另外一点需要注意的是,你必须重写Equals和GetHashCode方法使用CompositeId的实体。鉴于接受的答案映射文件,你的实体看起来像这样。

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

}