2

I am new to Entity Framework. I have a model as given below.

enter image description here

Since I need to access this from Silverlight I have added a DomainService

[EnableClientAccess()]
    public class DomainService1 : LinqToEntitiesDomainService<TESTDBEntities>
    {
        public IQueryable<Lecture> GetLectures()
        {
            return this.ObjectContext.Lectures;
        }      
        public IQueryable<ProjectGroup> GetProjectGroups()
        {
            return this.ObjectContext.ProjectGroups;
        }
        public IQueryable<Student> GetStudents()
        {
            return this.ObjectContext.Students;
        }
    }

I need to add a method to the domain service that returns List<Student> for a given project group id.

List<Student> GetStudentsByProject(int pgid)

OR

IQueryable<Student> GetStudentsByProject(int pgid)

Since this involves a join, I guess I have to change the Model.edmx as well as DomainService.cs file manually. How can I do this?

2 Answers 2

2

You shouldn't have to change the .edmx file.

public List<Student> GetStudentsByProject(int pgid)
{
    return this.ObjectContext.ProjectGroup.Where(pg => pg.pgid == pgid)
               .SelectMany(pg => pg.Students).ToList();
}
Sign up to request clarification or add additional context in comments.

4 Comments

Selecting the students through a query to ProjectGroup like in your example will probably result in a very complicated SQL statement containing sub-selects an union statements. Compared to a simple ObjectContext.Students.Where(x => x.ProjectGroup.pgid == projectGroupId) it produces ca. 7 times(!) as much SQL code.
I have changed the query to use SelectMany instead of Select, which will produce a much less complex SQL.
Why not just get the Students with the given Projectgroup Id directly?
@DennisTraub Doing what you suggest is of course perfectly good. I prefer to start at the top and find that more intuitive. At least for more complex queries. For this you could also write ObjectContext.ProjectGroup.FirstOrDefault(pg => pg.pgid == pgid).Students which I find equally intuitive, but it is a matter of taste I guess.
1

Just add another method to your domain service and you should be fine:

public IQueryable<Student> GetStudentsByGroup(int projectGroupId)
{
    return this.ObjectContext.Students
               .Where(x => x.ProjectGroup.pgid == projectGroupId);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.