Do you know why to use Entity Framework?

Last updated by Tiago Araújo [SSW] over 2 years ago.See history

Entity Framework allows you to provide a strongly typed object framework (ORM) over your database. This helps abstract the database away allowing it to be replaced with other technologies as needed.

using (SqlConnection conn = new SqlConnection())
    conn.ConnectionString = "Data Source=(local);Initial Catalog=Northwind;Integrated Security=True";
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = "SELECT * FROM Customers WHERE CompanyName LIKE '" + companyNameTextbox.Text + "%'";
    bindingSource1.DataSource = cmd.ExecuteReader();

Figure: Bad example - using ADO.NET and not strongly typed

var results = dbContext.Customers
    .Where(c => c.CompanyName.StartsWith(companyNameTextbox.Text));
customersBindingSource.DataSource = results;
// Or even
var results = dbContext.Customers
    .Where(c => c.CompanyName.StartsWith(companyNameTextbox.Text))
    .Select(c => new
customersBindingSource.DataSource = results;

Figure: Good example - at least 4 good reasons below

  1. Making queries that are independent from specific Database engine
  2. Strongly typed fields - SQL tables/entities have intellisense
  3. More readable and less code
  4. It's easy to chain more operation like OrderBy, GroupBy, FirstOrDefault, Count, Any and many more
  5. Developers are generally poor at writing SQL, so using code constructs makes writing queries much easier
We open source. Powered by GitHub