【问题标题】:Fluent Nhibernate Many to Many relationship issueFluent Nhibernate 多对多关系问题
【发布时间】:2015-02-13 22:02:23
【问题描述】:

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

我遇到的问题是我的 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();
}

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

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

【问题讨论】:

  • 您正在尝试做的是查询。 NHibernate 提供了几种方式,包括QueryOver、HQL。实体模型不会将查询优化到该级别。

标签: c# nhibernate fluent-nhibernate


【解决方案1】:

你应该使用的是batch-fetching

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)

还要检查这些是否有类似的东西:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    相关资源
    最近更新 更多