如何 select 特定列并使用 Entity Framework 连接表?
How to select specific columns and join tables with Entity Framework?
我需要从 SQL 服务器获取数据到我在 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
如何将上面的查询转换为 Entity Framework 的代码?
据我所知,管理 table 与用户和图书 table 一对多。
如果是这种情况,您可以在代码中向管理模型添加属性,并在从 SQL 管理 table.[=12 提取数据时包含这些 tables =]
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;}
}
这应该是您的管理 class。
对于 Entity Framework 中的查询,请尝试这样的操作:
public Managment GetData(int managmentId){
var data = context.Management
.Include(u => u.Users)
.Include(b => b.Books)
.FirstOrDefault(m => m.Id == managmentId);
}
使用 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
我需要从 SQL 服务器获取数据到我在 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
如何将上面的查询转换为 Entity Framework 的代码?
据我所知,管理 table 与用户和图书 table 一对多。
如果是这种情况,您可以在代码中向管理模型添加属性,并在从 SQL 管理 table.[=12 提取数据时包含这些 tables =]
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;}
}
这应该是您的管理 class。 对于 Entity Framework 中的查询,请尝试这样的操作:
public Managment GetData(int managmentId){
var data = context.Management
.Include(u => u.Users)
.Include(b => b.Books)
.FirstOrDefault(m => m.Id == managmentId);
}
使用 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