Foreign keys and entity

I am writing a simple golf record tracking program and I am seeing some strange results with entity relationships. My table Hole

has a foreign key relationship on it CourseId

and a column Course

Id

.

When I run next

using (var context = new DataAccess.Entities())
            {
                var courseId = 0;
                var holesInCourse = context.Holes.Where(x => x.CourseId == courseId);
                var holeList = holesInCourse.ToList();
            }

      

enter image description here

You can see that it returned a list of 9 holes for the given course 0

However, when I change the query to the following:

using (var context = new DataAccess.Entities())
            {
                var courseId = 0;
                var holesInCourse = context.Courses.FirstOrDefault(x => x.Id == courseId);
                var holeList = holesInCourse.Holes.ToList();
            }

      

enter image description here

I'm a bit lost as to why the second only returns 4 rows when it clearly has to do with 9. Is this how I am building my query?

+3


source to share


1 answer


In this code, var holesInCourse = context.Courses.FirstOrDefault(x => x.Id == courseId);

you are assigning courseId=0;

this is why you are not getting the correct answer. In this case, linq will try to take a list with a courseId=0

value from the database.



0


source







All Articles