When using QueryOver projections with type safe aliases, r# will warn that the value is always null. Here is a trick to remove the warning

No more R# warnings for nHibernate aliases

I dislike having R# warnings in code bases I work on, and try to leave every class I work on having a green status.

Here is a scenario

var entryAlias = default(Entry);
var entries = session.QueryOver<Entry>(()=>entryAlias);

In the above scenario R# will warn that entryAlias is always null, which is is, but I don't care, nHibernate is simply getting the type from the expression.

So I have created a simple static class:

/// <summary>
/// Simple helper class to remove r# warnings when using nHibernate aliases
/// </summary>
public static class Alias
{
    public static T For<T>()
    {
        return default(T);
    }
}

And we turn the above code into:

var entryAlias = Alias.For<Entry>();
var entries = session.QueryOver<Entry>(()=>entryAlias);

Which does not warn.

Happy Resharpering

nHibernateresharperc#
Posted by: Jake Ginnivan
Last revised: 22 Jul, 2011 01:35 AM

Comments

22 Jul, 2011 10:23 AM

The overload takes an expression tree Expression>, it uses that as a type safe way to define an alias for a table. It is really handy when you are doing projections using QueryOver.

There is no problem if you don't define an alias for that query or on a joined table. The API is not too bad really, but the r# warnings annoy me.

A more complete example from FunnelWeb

public IEnumerable<EntryRevision> Execute(ISession session, IDatabaseProvider databaseProvider)
{
    var entryAlias = Alias.For<Entry>();
    var entryRevision = Alias.For<EntryRevision>();

    var entryQuery = session
        .QueryOver<Revision>()
        .Where(r => r.RevisionNumber == Revision)
        .Left.JoinQueryOver(r => r.Entry, () => entryAlias)
        .Where(e => e.Name == PageName)
        .SelectList(list =>
        {
            list
                .Select(e => e.Id).WithAlias(() => entryRevision.Id)
                .Select(e => e.Author).WithAlias(() => entryRevision.RevisionAuthor)
                .Select(e => e.Body).WithAlias(() => entryRevision.Body)
                .Select(() => entryAlias.CommentCount).WithAlias(() => entryRevision.CommentCount)
                .Select(() => entryAlias.Name).WithAlias(() => entryRevision.Name)
                .Select(() => entryAlias.Published).WithAlias(() => entryRevision.Published)
                .Select(() => entryAlias.Status).WithAlias(() => entryRevision.Status)
                .Select(() => entryAlias.Title).WithAlias(() => entryRevision.Title);

            return list;
        })
        .TransformUsing(Transformers.AliasToBean<EntryRevision>());

    return entryQuery.Future<EntryRevision>();
}

See how I join over entry, and define an alias, then I am using that alias for both the projection source and target.

blog comments powered by Disqus