I have the following domain model
public interface IAppliedTo
{
public Guid Id { get; set; }
}
public class Widget
{
public DateTime DateCreated { get; set; }
public Guid Id { get; set; }
public ISet<IAppliedTo> AppliesTo { get; set; }
}
public class Master : IAppliedTo
{
public Guid Id { get; set; }
}
Widget mapping has AppliesTo defined as:
<set name="AppliesTo" table="WidgetAppliesTo" lazy="true" >
<key column="WidgetId"></key>
<many-to-any id-type="Guid" meta-type="int" >
<meta-value class="Master" value="1"/>
<column name="ObjectType" />
<column name="ObjectId" />
</many-to-any>
</set>
I am writing a query using QueryOver on Master, and I want to pull out the last CreatedDate for any Widget that applies to the Master.
Essentially I want something like:
Master mast=null;
Widget widg=null;
var widgetQuery=QueryOver.Of<Widget>(()=>widg);
var query = NHibernateSessionManager.Instance.GetSessionFrom()
.QueryOver<Master>(() => mast)
.Where(() => mast.Name == "Josh")
.SelectList(l =>
l.SelectSubQuery(widgetQuery.Where(() => widg.AppliesTo.Contains(mast))
.Select(Projections.Max(() => widg.DateCreated))
)
);
If my AppliesTo was a specific type I’d know how to do this, but how can I tell nHibernate to use ObjectId. Essentially I am trying to get this query:
SELECT *,(SELECT MAX(DateCreated)
FROM Widget
INNER JOIN WidgetAppliesTo
on Widget.Id=WidgetAppliesTo.ActivityId
WHERE objectId=[master].Id)
FROM [Master]
So far the best I’ve managed to do is to use a Sql Projection to add this in.
While this works I’d love to see a non-hacked solution