For example, a timesheet application: the model consists of a Project that can be configured to allow work against any Task, or only a specified subset of tasks.
When retrieving the data to log a timesheet for this Project, it needs to load the TaskOptions. Depending on the TasksMode of the Project, this could be all tasks in the database, or only the project's specified Tasks.
I have attempted the following EF linq query:
var availableTasks = dbContext.Projects
.Where(p => p.ProjectId == projectId)
.SelectMany(p => p.TasksMode == ProjectTasksMode.AllowAll
? dbContext.Tasks
.Select(t => new TaskOption {TaskId = t.TaskId, Name = t.Name})
: p.Tasks.Select(t => t.TaskId)
.Join(dbContext.Tasks, id => id, t => t.TaskId,
(tId, t) => new TaskOption {TaskId = tId, Name = t.Name}))
.ToList();
However I get the following System.NotSupportedException:
Unable to cast the type 'System.Linq.IQueryable1[[MyApp.TaskOption, MyApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' to type 'System.Collections.Generic.IEnumerable1[[MyApp.TaskOption, MyApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'. LINQ to Entities only supports casting EDM primitive or enumeration types.
I'm not sure how I would write this in SQL either, so am struggling to work out how to debug it. I could just use 2 separate db queries, but I think this should be possible.
.AsEnumerable(). So, it'd be:(tId, t) => new TaskOption {TaskId = tId, Name = t.Name})).AsEnumerable()Taskstable contains all possible tasks. TheProject.Tasksnavigation property points to an association table calledProjectTasks, that just links each project with a task, ie. a many - many relationship. That association table will only be populated when the project'sTaskMode != AllowAll