views:

556

answers:

3

Okay, so I'm doing my first foray into using the ADO.NET Entity Framework.

My test case right now includes a SQL Server 2008 database with 2 tables, Member and Profile, with a 1:1 relationship.

I then used the Entity Data Model wizard to auto-generate the EDM from the database. It generated a model with the correct association. Now I want to do this:

ObjectQuery<Member> members = entities.Member;
IQueryable<Member> membersQuery = from m in members select m;
foreach (Member m in membersQuery)
{
   Profile p = m.Profile;
   ...
}

Which halfway works. I am able to iterate through all of the Members. But the problem I'm having is that m.Profile is always null. The examples for LINQ to Entities on the MSDN library seem to suggest that I will be able to seamlessly follow the navigation relationships like that, but it doesn't seem to work that way. I found that if I first load the profiles in a separate call somehow, such as using entities.Profile.ToList, then m.Profile will point to a valid Profile.

So my question is, is there an elegant way to force the framework to automatically load the data along the navigation relationships, or do I need to do that explicitly with a join or something else?

Thanks

+2  A: 

Okay I managed to find the answer I needed here http://msdn.microsoft.com/en-us/magazine/cc507640.aspx. The following query will make sure that the Profile entity is loaded:

IQueryable<Member> membersQuery = from m in members.Include("Profile") select m;
Gerald
+1  A: 

I used this technique on a 1 to many relationship and works well. I have a Survey class and many questions as part of that from a different db table and using this technique managed to extract the related questions ...

context.Survey.Include("SurveyQuestion").Where(x => x.Id == id).First()

(context being the generated ObjectContext).

context.Survey.Include<T>().Where(x => x.Id == id).First()

I just spend 10mins trying to put together an extention method to do this, the closest I could come up with is ...

    public static ObjectQuery<T> Include<T,U>(this ObjectQuery<T> context)
    {
        string path = typeof(U).ToString();
        string[] split = path.Split('.');

        return context.Include(split[split.Length - 1]);
    }

Any pointers for the improvements would be most welcome :-)

WestDiscGolf
+1  A: 

On doing a bit more research found this ... StackOverflow link which has a post to Func link which is a lot better than my extension method attempt :-)

WestDiscGolf