【问题标题】:nhibernate fluent mapping to not include property in auto querynhibernate fluent映射不包括自动查询中的属性
【发布时间】:2014-04-09 09:03:53
【问题描述】:

我正在尝试为 NHibernate 中的一个类生成一个映射,该映射将映射到一个手写查询,以包含一个不在类映射相关的表中的字段。

表格如下:

Id int 
Name varchar(50)
Parent int

班级:

int Id {get; set;} 
string Name {get; set;} 
int ParentId {get; set;}
int ChildCount {get; set;}

映射:

x => x.Id, "Id" 
x => x.Name, "Name" 
x => x.Parent, "Parent" 
x => x.ChildCount, "ChildCount"

有一个自定义查询返回“ChildCount”作为完美映射到该类的属性,当该类用于与另一个类的关系中并且 NHibernate 隐式加载该类时会出现问题。有没有办法指定 ChildCount 映射应该存在,但仅用于将查询绑定到类,而不是用于自动创建 SQL 以直接从数据库加载对象。

在后一种情况下,NHibernate 失败,因为它创建了一个 SQL 查询

SELECT Id, Name, Parent, ChildCount FROM ...

对象作为关系的一部分被加载。

【问题讨论】:

    标签: c# sql nhibernate fluent-nhibernate fluent


    【解决方案1】:

    您可以使用Formula(string formula) 方法来映射此属性,并添加一个sql 子查询来执行此操作,例如:

    Map(x => x.ChildCount).Formula("select count(*) from Table where parent=id");
    

    这将导致一个子查询来计算有多少孩子,并在父列中传递 id。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-30
      相关资源
      最近更新 更多