简体   繁体   English

ASP.NET/SQL-使用外键从多个表中检索数据

[英]Asp.net/SQL - Retrieving data from multiple tables using foreign keys

I'm new to ASP.NET and SQL, and I'm trying to build a Web Forms project that will basically display data using grids. 我是ASP.NET和SQL的新手,我正在尝试构建一个Web窗体项目,该项目基本上将使用网格显示数据。

I'm using Entity Framework along with a Data Transfer Object and a Data Access Layer for displaying/editing data. 我正在使用实体框架以及数据传输对象和数据访问层来显示/编辑数据。

My issue is that I'm not sure what is the best way of retrieving data using foreign keys. 我的问题是我不确定使用外键检索数据的最佳方法是什么。

Example: 例:

Table 1 - Products 表1-产品

|(PK) Product ID | Product Name | Country ID(FK)

Table 2 - Countries 表2-国家

|(PK) Country ID | Country Name|

Final Result Should be: 最终结果应为:

Product ID | Product Name | Country Name|

What's the best way to accomplish that? 做到这一点的最佳方法是什么?

Thanks in advance 提前致谢

You can make LINQ query from this one. 您可以从这一查询中进行LINQ查询。 Better, you create one separate class and retrieve only data which you want. 更好的是,您可以创建一个单独的类并仅检索所需的数据。

SQL Query : SQL查询:

SELECT P.ProductID, P.ProductName, C.COuntryName FROM Products P
INNER JOIN ON Countries C ON C.CountryID = P.CountryID

Execute Query using EF : 使用EF执行查询:

context.Database.SqlQuery<ProductDTO>(query).ToList();

The best approach is use a projection to do that. 最好的方法是使用投影来做到这一点。 Your code will be similar to the code below: 您的代码将类似于以下代码:

context.Products.Select(x=>new ProductDto
{
   ProductId=x.ProductId,
   ProductName=x.Name,
   CountryName=x.Country.Name
});

Using projections you will ensure that is retrieving only the necessary data from DB. 使用投影,您将确保仅从DB中检索必要的数据。

Hope this helps! 希望这可以帮助!

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

相关问题 在C#ASP.NET Web API中使用2个外键从表中检索数据 - retrieving data from a table with 2 foreign keys in c# asp.net web api 如何使用 LINQ 表达式 ASP.NET MVC Entity Framework 使用外键更新多个表 - How to Update multiple tables with foreign keys using LINQ expression ASP.NET MVC Entity Framework 使用 C# 从 ASP.NET 中的 SQL Server 检索数据 - Retrieving data from SQL Server in ASP.NET using C# 从ASP.NET中的多个SQL表中选择多个列 - Select multiple columns from multiple SQL tables in ASP.NET 如何将两个表中的两个外键转发到第三个表中? ASP.NET 内核和 C# - How to forward two foreign keys from two tables into third table? ASP.NET Core and C# 使用linq-to-sql从多个表中检索数据 - Retrieving data from multiple tables using linq-to-sql 使用LINQtoSQL从ASP.NET MVC中的外键表中检索项目和值 - Retrieving Items and values from Foreign Key Table in ASP.NET MVC using LINQtoSQL 在ASP.NET Web表单中使用SQL Server在一个表中使用两个外键 - Two foreign keys in one table using SQL Server in asp.net webform asp.net mvc-使用实体框架6在第三个表中插入多个具有父级外键的记录 - asp.net mvc - Inserting multiple records in the third table having foreign keys to parent using entity framework 6 Asp.Net MVC 5汇总来自多个表的数据 - Asp.Net MVC 5 Summarize data from multiple tables
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM