How to use LINQ to Entities Queries in Entity Framework

By FoxLearn 8/1/2024 2:44:27 AM   201
LINQ (Language Integrated Query) is a powerful feature in C# that allows you to query various data sources, including Entity Framework (EF) data contexts.

When working with LINQ to Entities, you write queries against your EF data context to retrieve data from a database. These queries are translated into SQL by EF and executed against the database.

To fetch data from your sql database using the Entity Framework in c#.net, you can use linq select query with where clause in c# to query your data.

Query is an expression that retrieves data from a data source. Queries are often expressed in specialized query languages, such as SQL for relational databases and XQuery for XML.

A LINQ query operation consists of three actions such as, retrieving the data source or source, creating the query, and executing the query.

private void txtSearch_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        var sql = from c in db.Customers.Local
                  where c.CompanyName.Contains(txtSearch.Text)
                  select c;
        customerBindingSource.DataSource = sql.ToList();
    }
}

The snippet above allows you to search customer by compnayname like your search value. When executing your code, Linq automatically  translates into sql queries,  then automatically mapped to your object.

If you want to get a single Customer object and filter with CompanyName is 'Alfreds Futterkiste', you can use First or FirstOrDefault, as shown below.

Use where to filter results based on conditions.

using (NorthwindEntities db = new NorthwindEntities())
{    
    var customer = (from c in db.Customers
                where c.CompanyName == "Alfreds Futterkiste"
                select c).FirstOrDefault<Customers>();
}

To retrieve all entities from the NorthwindEntities table.

using (var context = new NorthwindEntities())
{
    var entities = context.Customers.ToList();
}

Use Select to project data into a new form.

using (var context = new NorthwindEntities())
{
    var names = context.Customers
                        .Select(e => e.CompanyName)
                        .ToList();
}