Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping Composite keys in Fluent NHibernate

I am new to Fluent NHibernate and have been unable to figure out how to map composite keys.

How can I do this? What approach do I need to take?

like image 942
pang Avatar asked Jan 15 '09 07:01

pang


3 Answers

There's a CompositeId method.

public class EntityMap : ClassMap<Entity> {   public EntityMap()   {       CompositeId()       .KeyProperty(x => x.Something)       .KeyReference(x => x.SomethingElse);   } } 
like image 155
James Gregory Avatar answered Oct 04 '22 19:10

James Gregory


if this is your first class

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

here is the second with a reference on Entity

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

      }
    }
like image 31
Lars Hildebrandt Avatar answered Oct 04 '22 18:10

Lars Hildebrandt


Another thing to note is that you must override the Equals and GetHashCode methods for an entity using a CompositeId. Given the accepted answers mapping file, your entity would look like this.

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

}
like image 23
Kyle Mountney Avatar answered Oct 04 '22 18:10

Kyle Mountney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!