Search code examples
c#entity-frameworkef-code-first

How to select specific columns and join tables with Entity Framework?


I need to get data from SQL Server to my data grid view in Winforms

SELECT 
    Managements.OrderID, Managements.BookReturnDate, Managements.Money,
    Books.bookName
FROM
    Managements
INNER JOIN 
    Users ON Users.UserID = Managements.Username_UserID
INNER JOIN  
    Books ON Books.bookID = Managements.Book_bookID

How can I convert the query above to a code for Entity Framework?


Solution

  • As far as I can see Management table has one to many with User and Book tables.

    If that is the case you can add, properties to the Management model in code and include these tables when you pull data from SQL Management table.

    public class Management{
        public int ManagmentId { get; set; }
        public int UserId { get; set;}
        public List<User> Users { get; set;}
        public int BookId { get; set;}
        public List<Book> Books { get; set;}
    } 
    

    This should be your Management class. For the query in Entity Framework try something like this:

    public Managment GetData(int managmentId){
        var data = context.Management
           .Include(u => u.Users)
           .Include(b => b.Books)
           .FirstOrDefault(m => m.Id == managmentId); 
     }