Just Can't get Entity Framework to pull what I want
Ok, I am not having much luck with this. I am new to Entity Framework, and have been fighting with this one little thing since yesterday.
Here are my tables:
- Clients (id, clientname)
- Projects (id, projectname, clientid)
- Tasks (id, taskname, projectid, statusid)
- TaskStatuses (id, statusname)
In code I am only working with one project at a time, and here is how I load that project with EF:
thisProject = (from p in dataEntity.projects
where p.id == projectID
select p).FirstOrDefault();
Then later when I load the tasks:
thisProject.Tasks.Load();
Then I se开发者_C百科t the datasource of a DevExpress XtraGrid to the loaded Tasks:
taskGridControl.DataSource = thisProject.Tasks;
Up until this point everything works as expected, and the grid shows all of the tasks for the project I have loaded. But, I also want to show the Task statusname field, and that is stored in a different table.
This was very easy with a sql join, but for the life of me I cannot figure this out.
It's easiest to select your data out into a class that's custom-made for this grid view:
from t in dataEntity.tasks
where t.projectId == projectID
select new TaskInfo
{
ProjectName = t.project.projectname,
TaskName = t.taskname,
StatusName = t.taststatus.statusname
}
Sounds like your task status table hasn't loaded.
I think you may have more luck with EF version 4 - then you wouldn't need the 'thisProject.Tasks.Load()' line, and the task status table would be loaded lazily for you automatically as well.
Make sure the other table is loaded. Assuming the other table is called
TaskStatus
,thisProject.Tasks.TasksStatusReference.Load();
In the designer, under databindings, just reference it as you would any other field, with the
TaskStatus.
qualifier before it:TaskStatus.Status
.
Just a few more ideas to add to those already suggested.
This first one may not apply but in case it does... :) If, at the time you load the project you already know you want the tasks and status, you could eager load that related data along with the project.
thisProject = (from p in dataEntity.projects.Include("Tasks.TasksStatuses") where p.id == projectID select p).FirstOrDefault();
(I'm guessing at the names of your navigation properties.)
Another possibility to consider...are you using asp.net? You may no longer have access to the context when you attempt to lazy load the status data.
精彩评论