简体   繁体   English

如何使用JOIN从SQL查询创建ADO.NET实体数据模型?

[英]How to create ADO.NET Entity Data Model from SQL query with JOIN?

I have created .NET Console Application (C#). 我已经创建了.NET控制台应用程序(C#)。 My SQL Server database has 3 tables. 我的SQL Server数据库有3个表。 I created ADO.NET Entity Data Models for those tables in my project by Entity Framework Database First guide. 我通过Entity Framework Database First指南为项目中的那些表创建了ADO.NET实体数据模型。 They work fine, but I need to create another model for my SQL Query which is following: 它们工作正常,但是我需要为我的SQL查询创建另一个模型,如下所示:

SELECT users.name, users.userid, COUNT(userlogs.userid)
FROM users
LEFT JOIN userlogs ON users.userid = userlogs.userid
GROUP BY users.name, users.userid

It is expected to get users names, userids and counts of logs in userlogs table. 可以在userlogs表中获取用户名,用户ID和日志计数。 Then my mission is to loop through these and create string which I use to show "Top 5 most causes for logs". 然后,我的任务是遍历这些内容并创建一个字符串,该字符串用于显示“最常见的5个日志原因”。
How should I go about creating required DbSet and Model like the generated ones from tables? 我应该如何创建所需的DbSet和模型,就像从表中生成的那样?

I'm using Visual Studio 2017, SQL Server 2012, Entity Framework 6.4, .NET 4.6.x. 我正在使用Visual Studio 2017,SQL Server 2012,实体框架6.4,.NET 4.6.x.

There are 2 ways to do it 有两种方法可以做到这一点

  1. Create a stored procedure and write your query there. 创建一个存储过程,并在其中编写查询。 Then import your stored procedure like you imported your tables. 然后像导入表一样导入存储过程。 There is an option to import stored procedure. 有一个导入存储过程的选项。 This will create a function in your edmx classes which you can utilize for looping through the data 这将在您的edmx类中创建一个函数,可用于循环遍历数据

  2. Use LINQ(preferred method) in your controller or any business logic class and create the query through either lambda expression or SQL to LINQ to retrieve data from database 在控制器或任何业务逻辑类中使用LINQ(首选方法),并通过lambda表达式或SQL创建到LINQ的查询以从数据库检索数据

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

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