简体   繁体   中英

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

I have created .NET Console Application (C#). My SQL Server database has 3 tables. I created ADO.NET Entity Data Models for those tables in my project by Entity Framework Database First guide. They work fine, but I need to create another model for my SQL Query which is following:

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. Then my mission is to loop through these and create string which I use to show "Top 5 most causes for logs".
How should I go about creating required DbSet and Model like the generated ones from tables?

I'm using Visual Studio 2017, SQL Server 2012, Entity Framework 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

  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

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