Note that there are some explanatory texts on larger screens.

plurals
  1. PONHibernate Group By Many-to-Many Association
    primarykey
    data
    text
    <p>I need to execute a query that joins two tables, groups by a value, and returns the group key and a count.</p> <pre><code>CREATE TABLE Message( ID INT NOT NULL , Note NVARCHAR(128)); CREATE TABLE Message_Users( MessageID INT NOT NULL , UserID NVARCHAR(128) NOT NULL); </code></pre> <p>I need to execute this query:</p> <pre><code>SELECT mu.UserID, COUNT(m.ID) FROM Message m JOIN Message_Users mu ON m.ID = mu.MessageID GROUP BY mu.UserID; </code></pre> <p>How can I do this using NHibernate? The Message table is mapped as follows:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="DataModel" namespace="DataModel.Message"&gt; &lt;class name="Message" table="Message"&gt; &lt;id name="ID"&gt; &lt;generator class="native" /&gt; &lt;/id&gt; &lt;bag name="AssociatedUsers" table="Message_Users" lazy="false"&gt; &lt;key column="MessageID" /&gt; &lt;element column="UserID" type="System.String" /&gt; &lt;/bag&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre> <p>I have looked at several other questions, but none meet quite this use case (plenty of GroupBy, but not with an association; <a href="https://stackoverflow.com/questions/3900779/nhibernate-queryover-with-manytomany">plenty of join, but not with a group by</a>)</p> <p>Two directions I have started going in:</p> <p>// First attempt</p> <pre><code>// Doesn't work as message.AssociatedUsers is a collection, so mu.Key is actually a collection var query = transactionContext.Session.Query&lt;Message&gt;(); var r = from message in query group message by message.AssociatedUsers into mu select new {UserID = mu.Key, Count = mu.Count()}; </code></pre> <p>// Second attempt</p> <pre><code>var query = transactionContext.Session.QueryOver&lt;Message&gt;(); var join = query.Right.JoinQueryOver&lt;string&gt;(_message =&gt; _message.AssociatedUsers); var select = join.Select( // Select generic parameter doesn't seem to be related to the type of the join (&lt;Message, string&gt;) Projections.Group&lt;string&gt;(... </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload