To query a database with LINQ in C#, you can use Entity Framework (EF), which is an object-relational mapping (ORM) framework. EF allows you to write queries using LINQ syntax and it will translate them into SQL queries to interact with the database.
Assuming you already have a database set up and an EF data model, you can query the database in C# using LINQ as follows:
main.cs512 chars12 lines
In this example, MyDbContext
is the EF data model that represents your database schema, Customers
is a DbSet in the data model, and Name
and OrderDate
are properties of the corresponding entity classes, which map to columns in the database.
Note that the ToList()
method is called at the end of each query to execute the query and return the results as a list. Also, the last query uses the Sum
method to calculate the total sales by multiplying the order quantity and unit price for each product and then summing up the results.
gistlibby LogSnag