简体   繁体   中英

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?

Use linq

 var s = from management in dbContext.Managements
         join user in dbContext.Users on users.UserId equals management.Username_UserID
         join book in dbContext.Books on book.BookId equals management.Book_bookID
         select management.OrderID, management.BookReturnDate, management.Money,
            book.bookName

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); 
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM