C# – Nhibernate DetachedCriteria: Find entities where a property’s property match a value

asp.netcdetachedcriterianetnhibernate

I have two following classes:

public class User
{
    public virtual Guid Id { get; set; }
    public virtual UserCredentials Credentials { get; set; }

    // other stuff

    protected User() { }
}

public class UserCredentials
{
    public virtual Guid Id { get; set; }
    public virtual string UserName { get; set; }

    // other stuff

    protected UserCredentials() { }
}

I want to create a detached criteria that finds all users where Credentials.UserName = "someuser", but I cannot get it right.. I have tried the following:

DetachedCriteria.For<User>().Add(Expression.Eq("Credentials.UserName", "someuser");

but I get an exception saying

"could not resolve property:
Credentials.UserName of:
DataLinkNord.Domain.User"

Any help would be appreciated..

Best Answer

I've run into this issue before myself (although I'm a Java user), but the way around it for me was to use the "addAlias()" call first... something like:

DetachedCriteria.For<User>().AddAlias("Credentials", "Credentials").Add(Expression.Eq("Credentials.UserName", "someuser");