NHibernate Group由多对多协会组成

时间:2012-08-27 16:56:42

标签: c# linq nhibernate

我需要执行一个查询,该查询按值连接两个表,组,并返回组密钥和计数。

CREATE TABLE Message(
  ID INT NOT NULL
, Note NVARCHAR(128));

CREATE TABLE Message_Users(
  MessageID INT NOT NULL
, UserID NVARCHAR(128) NOT NULL);

我需要执行此查询:

SELECT mu.UserID, COUNT(m.ID)
FROM Message m
JOIN Message_Users mu
   ON m.ID = mu.MessageID
GROUP BY mu.UserID;

如何使用NHibernate执行此操作? Message表映射如下:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="DataModel" namespace="DataModel.Message">
  <class name="Message" table="Message">
    <id name="ID">
      <generator class="native" />
    </id>
    <bag name="AssociatedUsers" table="Message_Users" lazy="false">
      <key column="MessageID" />
      <element column="UserID" type="System.String" />
    </bag>
  </class>
</hibernate-mapping>

我已经查看了其他几个问题,但没有一个问题符合这个用例(很多GroupBy,但没有关联; plenty of join, but not with a group by

我已经开始进入的两个方向:

//首次尝试

// Doesn't work as message.AssociatedUsers is a collection, so mu.Key is actually a collection
var query = transactionContext.Session.Query<Message>();    
var r = from message in query
        group message by message.AssociatedUsers into mu
        select new {UserID = mu.Key, Count = mu.Count()};

//第二次尝试

var query = transactionContext.Session.QueryOver<Message>();
var join = query.Right.JoinQueryOver<string>(_message => _message.AssociatedUsers);
var select = join.Select(
      // Select generic parameter doesn't seem to be related to the type of the join (<Message, string>)
    Projections.Group<string>(... 

1 个答案:

答案 0 :(得分:2)

未经测试

// Option 1
var r = from message in Session.Query<Message>()
        from userid in message.AssociatedUsers
        group userid by userid into g
        select new { UserID = g.Key, Count = g.Count() };

// Option 2
string userId = null;
var r = Session.QueryOver<Message>()
    .JoinQueryOver<string>(m => m.AssociatedUsers, () => userId)
    .SelectList(list => list
        .SelectGroup(() => userid)
        .Select(Projections.Count()))
    .List<object[]>();