C# Language Entity Framework Connections


Example

Entity Framework exposes abstraction classes that are used to interact with underlying databases in the form of classes like DbContext. These contexts generally consist of DbSet<T> properties that expose the available collections that can be queried :

public class ExampleContext: DbContext 
{ 
    public virtual DbSet<Widgets> Widgets { get; set; } 
}

The DbContext itself will handle making the connections with the databases and will generally read the appropriate Connection String data from a configuration to determine how to establish the connections :

public class ExampleContext: DbContext 
{ 
    // The parameter being passed in to the base constructor indicates the name of the 
    // connection string
    public ExampleContext() : base("ExampleContextEntities")
    {
    }

    public virtual DbSet<Widgets> Widgets { get; set; } 
}

Executing Entity Framework Queries

Actually executing an Entity Framework query can be quite easy and simply requires you to create an instance of the context and then use the available properties on it to pull or access your data

using(var context = new ExampleContext())
{
      // Retrieve all of the Widgets in your database
      var data = context.Widgets.ToList();
}

Entity Framework also provides an extensive change-tracking system that can be used to handle updating entries within your database by simply calling the SaveChanges() method to push changes to the database :

using(var context = new ExampleContext())
{
      // Grab the widget you wish to update
      var widget = context.Widgets.Find(w => w.Id == id);
      // If it exists, update it
      if(widget != null)
      {
           // Update your widget and save your changes
           widget.Updated = DateTime.UtcNow;
           context.SaveChanges();
      }
}