NHibernate 3.2中的一对多映射通过代码映射

时间:2012-03-05 06:50:01

标签: nhibernate one-to-many mapping-by-code

我正在尝试学习NHibernate 3.2 built-in mapping by code api NOT Fluent NHibernate )。你能帮我勾画出这些实体之间的一对多关系吗?

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

更新

我像这样映射Id

Id(
    t => t.Id,
    t => {
        t.Generator(Generators.HighLow, g => g.Params(new { max_low = 100 }));
        t.Column(typeof(TEntity).Name + "Id");
    });

1 个答案:

答案 0 :(得分:8)

这并不像听起来那么容易,因为我们现在不是你的主要关键策略,如果你正在使用包或套装,你使用什么级联等等......但是说,下面是一个应该让你开始的小样本......

成员映射: -

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

对于评论映射: -

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

编辑我还应该指出,您确实需要了解XML映射的基础知识,并了解UpdateInsert等每个属性对您的方式的影响。模型是持久的。