query a database with linq in csharp

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.cs
using(var context = new MyDbContext())
{
    // Query all customers whose name starts with "John"
    var customers = context.Customers.Where(c => c.Name.StartsWith("John")).ToList();
    
    // Query all orders that were placed in the last 7 days
    var orders = context.Orders.Where(o => o.OrderDate > DateTime.Now.AddDays(-7)).ToList();
    
    // Query the total sales for a specific product
    var productSales = context.Orders.Where(o => o.ProductId == productId).Sum(o => o.Quantity * o.UnitPrice);
}
512 chars
12 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