Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting data in Entity Framework

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?

like image 546
Kevin Avatar asked Feb 25 '26 10:02

Kevin


1 Answers

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.

like image 166
Christos Avatar answered Feb 27 '26 00:02

Christos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!