query a database with a linq query in csharp

To query a database using LINQ in C#, you first need to establish a connection to the database. Once you have established a connection, you can use LINQ to write a query. Here's an example:

main.cs
using (var db = new YourDbContext())
{
    var query = from item in db.Items
                where item.Price > 10 && item.QuantityInStock > 0
                select item;

    foreach (var item in query)
    {
        Console.WriteLine(item.Name);
    }
}
257 chars
12 lines

In the code above, YourDbContext is the name of the DbContext class generated by Entity Framework. You can replace it with the name of your own DbContext class.

The query selects all items from the Items table where the price is greater than 10 and the quantity in stock is greater than 0. The query is then executed using a foreach loop to print the names of the items that match the criteria.

Keep in mind that you need to have a reference to the Entity Framework library in your project and the necessary namespaces must be imported.

gistlibby LogSnag