How to use LINQ to Entities Queries in Entity Framework

By FoxLearn 2/16/2024 3:16:35 PM   82
This post shows you how to Query in LINQ to Entities using c# code.

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

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