在Fluent NHibernate中映射复合键

时间:2009-01-15 07:16:03

标签: fluent-nhibernate

我是流利的NHibernate的新手。现在我遇到映射复合键的一个问题。 任何人都可以指出网址或样本吗?

4 个答案:

答案 0 :(得分:50)

有一种CompositeId方法。

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

答案 1 :(得分: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();

      }
    }

答案 2 :(得分:4)

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

}

答案 3 :(得分: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