流利的Nhibernate多对多关系问题

时间:2015-02-13 22:02:24

标签: c# nhibernate fluent-nhibernate

我的情况是我的数据库中有三个表。一个包含客户,一个包含客户组,然后是一个表将它们链接在一起。

我遇到的问题是我的nHibernate查询不能正确加入它们,我不确定我是否遗漏了一些东西。

客户群体的映射

public CustomerGroupMapping() {
      Table("tbCustomerGroups");
      // TODO: Revisit Lazy loading
      //LazyLoad();
      Id(x => x.customerGroupId)
        .GeneratedBy.Identity()
        .Column("Customer_Group_ID");
      Map(x => x.customerGroup)
        .Column("Customer_Group")
        .Length(50);
      Map(x => x.editDisabled)
        .Column("EditDisabled")
        .Not.Nullable();

      HasManyToMany<CustomerModel>(x => x.customers)
        .Table("tbCustomerGroupsRelationship")
        .ParentKeyColumn("Customer_Group_ID")
        .ChildKeyColumn("Customer_ID")
        .Inverse();
    }

为客户制作地图

public CustomerMapping() {
  Table("tbCustomers");
  // TODO: Revisit Lazy load
  LazyLoad();
  Id(x => x.customerId)
    .GeneratedBy.Identity()
    .Column("Customer_ID");
  Map(x => x.customerTypeId)
    .Column("Customer_Type_ID")
    .Not.Nullable()
    .Precision(10);

  // A Customer has many users
  HasMany<UserModel>(x => x.users)
    .KeyColumn("Customer_ID");

  // A Customer can belong to many groups
  HasManyToMany<CustomerGroupModel>(x => x.groups)
    .Table("tbCustomerGroupsRelationship")
    .ParentKeyColumn("Customer_ID")
    .ChildKeyColumn("Customer_Group_ID")
    .Not.Inverse();
}

问题似乎是,当我找到客户时,我希望看到该客户的客户群。 (IE给我客户10,获得有客户10的客户组,然后给我该组中的所有其他客户)

有没有办法更改这些映射以正确加载而不会生成大量的select语句,因为这正是Log4net向我展示的。

1 个答案:

答案 0 :(得分:1)

您应该使用批量提取

19.1.5. Using batch fetching

简而言之,此优化设置会将大量查询减少到几个批次。它提高了性能并支持在一个根实体上查询(不需要FETCH策略作为SELECT)

使用 .BatchSize(xx) 扩展您的课程和集合映射。类应具有此映射:

public CustomerGroupMapping() 
{
    Table("tbCustomerGroups");
    BatchSize(25);
    ...

public CuustomerMapping() 
{
    Table("tbCustomers");
    BatchSize(25);
    ...

应该扩展收藏

HasManyToMany<CustomerModel>(x => x.customers)
   ...
   .BatchSize(25)

HasManyToMany<CustomerGroupModel>(x => x.groups)
   ...
   .BatchSize(25)

同样检查这些类似的东西:

另外,我的建议是 - 不要使用多对多。我更喜欢将配对表作为第一级对象...也许请检查这些:

相关问题