views:

24

answers:

1

We're trying to make it easy to write strongly-typed code in all areas of our system, so rather than setting var sortColumn = "FirstName" we'd like to say sortOption = (p => p.FirstName). This works great if the sortOption is of type Expression<Func<Person, object>> (we actually use generics in our code but that doesn't matter). However, we run into problems for many-to-many relationships because this notation breaks down.

Consider this simple code:

    internal class Business
    {
        public IQueryable<Address> Addresses { get; set; }
        public string Name { get; set; }
    }

    internal class Address
    {
        public State MyState { get; set; }
    }

    internal class State
    {
        public string Abbreviation { get; set; }
        public int StateID { get; set; }
    }

Is it possible to have this sort of MemberExpression to identify the StateID column off of a business? Again, the purpose of using this is not to return a StateID object, it's to just identify that property off of that entity (for sorting, filtering, and other purposes).

It SEEMS to me that there should be some way to do this, even if it's not quite as pretty as foo = business.Addresses.SomeExtension(a => a.State.StateID);. Is this really possible?

If more background is needed, take a look at this old question of mine. We've since updated the code significantly, but this should give you the general detailed idea of the context behind this question.

A: 

In one area, we have found that the following syntax works, although it is non-ideal:

business.Addresses.First().State.StateID;

This works when we're using Entity Framework and are trying to have a strongly-typed .Include() method off of our Context's entity collections. However, there are areas where this is not working for us, so we're hoping there's a better solution. Otherwise, I suspect we can work around the problems and jump through some hoops in the other areas to make this work.

Jaxidian
This is a non-ideal solution but is what we're doing for now. Seems to work pretty well despite it seeming not quite right.
Jaxidian