views:

42

answers:

1

Using EF how do i access values in a parent property when accessing a list of child objects.

i.e. I have a Project object and Timesheet object

Project
Id
Name
...

TimeSheet
ProjectId
UserId
Date
TimeSpent
...

I understand how to get back a Project and its related Timesheets but what if I want to get back all of the timesheets for a given user and then simply display the project name with each timesheet record.

e.g. ProjectName, Date, TimeSpent

Is it best practice to create a new entity to shape that result set or should i just be able to return IEnumerable and get access to the .Project.Name field.

This is super easy using Linq to Sql or just straight up ADO.net/SPs etc but Its killing me on EF..

Any ideas?

A: 

Children always have a relationship with their parents. In your case, it's probably called something like "TimeSheet.Project". So you can write a query like:

var q = from u in Context.Users
        where u.UserId == userId
        from ts in u.TimeSheets
        select new 
        {
            ProjectName = ts.Project.Name,
            Date = ts.Date,
            TimeSpent = ts.TimeSpent
        };
Craig Stuntz
Thanks. So if you're using a repository pattern would you project this into a new entity that can be passed through the layers or do you just pass through the anonymous type?
Chet
Anonymous types are tricky to return. Your method probably needs to return something like IQueryable<SomeType> So for the Repository pattern, in this case, I'd suggest returning an IQueryable<SomePOCO>, with SomePOCO created for the purpose.
Craig Stuntz