2

I'm trying to learn NHibernate 3.2 built-in mapping by code api (NOT Fluent NHibernate). Can you help me to map a one-to-many relationship between these entities please?

public class Member {
    public virtual int Id { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
}

public class Comment {
    public virtual int Id { get; set; }
    public virtual Member { get; set; }
}

UPDATE:

I map the Id like this:

Id(
    t => t.Id,
    t => {
        t.Generator(Generators.HighLow, g => g.Params(new { max_low = 100 }));
        t.Column(typeof(TEntity).Name + "Id");
    });
amiry jd
  • 27,021
  • 30
  • 116
  • 215

1 Answers1

8

This is not as easy as it sounds as we don't now your primary key strategy, if you are using bag's or sets, what cascading you use etc... However said, below is a small sample that should get you started...

The member mapping:-

//note: bag could be Set
public class MemberMapping : ClassMapping<Member> {
  public MemberMapping() {
    Id(x => x.Id, x => { x.Generator(...); etc... });
    Bag(x => x.CmsRegionContentList, bag => {
          bag.Inverse(true); // Is collection inverse?
          bag.Cascade(Cascade.DeleteOrphans); //set cascade strategy
          bag.Key(k => k.Column(col => col.Name("MemberId"))); //foreign key in Comment table
    }, a => a.OneToMany());
  }
}

And for the comment mapping:-

public class CommentMapping : ClassMapping<Comment> {
    public CommentMapping() {
      Id(x => x.Id, x => { x.Generator(...); etc... });
      ManyToOne(x => x.Page, x => {
          x.Column("MemberId"); 
          x.Update(false); //either True or False
          x.Insert(false); 
          x.Fetch(FetchKind.Join); //fetch join or select
        });
      }
    }

edit I should also point out that you really need to learn the basics of XML mapping and see what each attribute like Update and Insert actually does to the way your model is persisted.

Rippo
  • 22,117
  • 14
  • 78
  • 117
  • Thanks. I'm just new to NH and I dont know about xml or Fluent. I update the Q and add primary key strategy there. thanks in advanced – amiry jd Mar 05 '12 at 08:55
  • Beware of using the Update, Insert, and Fetch commands on the ManyToOne part - this overrides, or at least hides, the default behaviors and could lead to unexpected results. This would be made worse if you later implemented a convention. – Fourth Mar 05 '12 at 16:15
  • True, It should be noted that this is an example of how you could put things together, it may not be the defaults that you want. – Rippo Mar 05 '12 at 16:22