3

I have an Entity Framework Model in my project: enter image description here

In the past, I would use a LINQ statement to get the data about a book from both tables:

var books = (from book in db.Books
             join author in db.Authors on book.AuthorId equals author.AuthorId
             select new { book.Title, author.Name, book.Price }).ToList();

dataGridView1.DataSource = books;

As you can see, this code just joins the two tables on AuthorID and returns the results as a List.

But, now that I'm trying to use Entity Framework, I was wondering how to accomplish this same objective? I mean, since I have the relationship between the Book file and the Author file via AuthorId, isn't there a way I can just say "Give me the book data based on this model" and it will return a dataset comprised of data from both entities? I hope I'm not being obtuse, I just figured since there was an association described between the two entities, that I wouldn't have to do a join in a LINQ query to get the data. My thoughts are, the data should already be linked together, via the model and the described association. Does this make sense?

0

1 Answer 1

3

You could try this one:

var books = (from book in db.Books  
             select new { book.Title, book.Author.Name, book.Price }).ToList();

In other words, you can use te Navigation Properties, to do so.

Sign up to request clarification or add additional context in comments.

5 Comments

Cant this result in null reference exception if there is no author for the book ? Or will it just skip it ?
@astian it will throw an exception. You have to test it. But if your DB schema has a NOT NULLon the foreign key, no problem, lazy loading will do the rest and no null pointer exception possible.
@Christos, What makes you think that?
This worked perfectly. I also removed an Author from the table, re-ran the project, and received no exception. Only a blank field for Author appeared in my datagrid. As soon as the time is up, I'll mark this as the answer.
@haim770 are you refer to the answer or the comment that I deleted, since I was wrong?

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.