开发者

Querying on the properties of a private reference

I have a class that is many-to-one with its parent. I'd like to expose the parent's properties through the child without exposing the parent directly. I'd also like to query on and order by those properties.

Classes

public class Organization
{
    public virtual string Name { get; set; }
    public virtual bool IsNonProfit { get; set; }
}

public class Contact
{
    private Organization _organization;
    public virtual string OrganizationName 
        { get { return _organization.Name; } }
    public virtual bool OrganizationIsNonProfit 
        { get { return _organization.IsNonProfit; } }
}

Mapping

public class OrganizationMap : ClassMap<Organization>
{
    public OrganizationMap()
    {
        Ma开发者_StackOverflow中文版p(x => x.Name);
        Map(x => x.IsNonProfit);
    }
}

public class ContactMap : ClassMap<Contact>
{
    public ContactMap()
    {
        References<Organization>(Reveal.Member<Contact>("_organization"))
            .Access.CamelCaseField();
    }
}

Query

public class Example
{
    private ISessionFactory _sessionFactory;

    public Example(ISessionFactory sessionFactory)
    {
        _sessionFactory = sessionFactory;
    }

    public IEnumerable<Contact> DoQuery(int forPage, int rowsPerPage)
    {
        using (var session = _sessionFactory.OpenSession())
        {
            return session.Query<Contact>().OrderBy(x => x.OrganizationName)
                .Skip((forPage - 1) * rowsPerPage).Take(rowsPerPage);
        }
    }
}

The problem is that this results in a "Could not resolve property: OrganizationName" error. It looks like I could map those fields with a formula, but then I'd end up with a sub-select for each field on a table that's already joined into my query. Alternatively, I could wrap the Contact's organization with a public getter and change my query to OrderBy(x => x.Organization.Name). That leaves me with a Law of Demeter violation though.

Am I off track? How should I handle this?

edited to show paging


You can't use non-mapped properties in queries. How should NHibernate know how to create a SQL condition for it? In your case it might be easy, but what if you'd have a call to a method or some complicated logic in that property?

So yes, you need at least a public getter property.

Alternatively, do the sorting in memory (after NHibernate has executed the query).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜