简体   繁体   English

是否可以使用实体框架从 C# 中的几个表中获得加入 SQL 查询的结果?

[英]Is it possible to get result from joined SQL query from several tables in C# with Entity Framework?

I am using.Net Core with C# and Entity Framework.我正在使用.Net Core 与 C# 和实体框架。 I need to get data for reporting and it requires joins with several tables.我需要获取用于报告的数据,它需要连接多个表。

My question is, what is the best way to call the SQL query and pass the result to a client application?我的问题是,调用 SQL 查询并将结果传递给客户端应用程序的最佳方法是什么?

If the number of tables used is less than 3 or 4, we can use the EF join to get the data from multiple tables.如果使用的表数量少于 3 或 4,我们可以使用 EF 连接从多个表中获取数据。

Sample linq Join样品 linq 加入

var q=(from pd in dataContext.tblProducts 
 join od in dataContext.tblOrders on pd.ProductID equals od.ProductID 
 join ct in dataContext.tblCustomers 
 on new {a=od.CustomerID,b=od.ContactNo} equals new {a=ct.CustID,b=ct.ContactNo} 
 orderby od.OrderID 
 select new { 
 od.OrderID,
 pd.ProductID,
 pd.Name,
 pd.UnitPrice,
 od.Quantity,
 od.Price,
 Customer=ct.Name //define anonymous type Customer
 }).ToList();

If the number of tables used is more than that I suggest you to implement a Stored Procedure and use it to get the data.如果使用的表数量超过我建议您实现存储过程并使用它来获取数据。 You can still use the EF to call the SPROC and bind the data to any custom DTO class.您仍然可以使用 EF 调用 SPROC 并将数据绑定到任何自定义 DTO class。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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