41

我是 Fluent NHibernate 的新手,一直无法弄清楚如何映射复合键。

我怎样才能做到这一点?我需要采取什么方法?

4

4 回答 4

52

有一个CompositeId方法。

public class EntityMap : ClassMap<Entity>
{
  public EntityMap()
  {
      CompositeId()
      .KeyProperty(x => x.Something)
      .KeyReference(x => x.SomethingElse);
  }
}
于 2009-01-15T08:55:54.153 回答
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();

      }
    }
于 2009-05-13T12:49:11.653 回答
5

要注意的另一件事是,您必须使用 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;
        }
    }

}
于 2015-06-30T16:42:37.383 回答
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

于 2012-12-07T09:01:21.830 回答