Database Reference
In-Depth Information
3-5. Finding a Master That Has Detail in a Master-Detail
Relationship
Problem
You have two entities in a one-to-many association (aka Master-Detail), and you want to find all the master entities
that have at least one associated detail entity.
Solution
Imagine that you have a model for blog posts and the comments associated with each post. Some posts have lots of
comments. Some posts have few or no comments. The model might look something like the one shown in Figure 3-6 .
Figure 3-6. A model for blog posts and the associated comments
You want to find all of the blog posts that have at least one comment. To do this using either LINQ to Entities or
Entity SQL, follow the pattern in Listing 3-10.
Listing 3-10. Finding the Masters That Have Detail Using Both LINQ and Entity SQL
using (var context = new EFRecipesEntities())
{
// delete previous test data
context.Database.ExecuteSqlCommand("delete from chapter3.blogpost");
context.Database.ExecuteSqlCommand("delete from chapter3.comment");
// add new test data
var post1 = new BlogPost { Title = "The Joy of LINQ",
Description = "101 things you always wanted to know about LINQ" };
var post2 = new BlogPost { Title = "LINQ as Dinner Conversation",
Description = "What wine goes with a Lambda expression?" };
var post3 = new BlogPost {Title = "LINQ and our Children",
Description = "Why we need to teach LINQ in High School"};
var comment1 = new Comment {
Comments = "Great post, I wish more people would talk about LINQ" };
var comment2 = new Comment {
Comments = "You're right, we should teach LINQ in high school!" };
post1.Comments.Add(comment1);
post3.Comments.Add(comment2);
 
Search WWH ::




Custom Search