Entity Framework Core DbContext Updated

4.4 (5 votes)

Redesigning a framework from the ground up provides an opportunity to implement an improved API. The team working on Entity Framework Core have certainly grabbed that opportunity in respect of the DbContext class, which sees a bunch of new data manipulation methods not available in Entity Framework 6 or earlier.

In previous versions of Entity Framework that include the DbContext (EF 4.1.1 onwards), data manipulation (create, update and delete) operations are performed against the relevant entity's DbSet property. In Entity Framework Core, these operations can now also be performed directly against the DbContext.

Adding Data

The DbContext provides a couple of methods for adding data: Add and AddRange. There are two versions of the Add method which is designed for adding a single instance of an entity to the database - a generic one and one that takes an object as a parameter. You are most likely to use the generic version:

var author = new Author { FirstName = "William", LastName = "Shakespeare" };
context.Add(author);
context.SaveChanges();

The Add method results in the entity being tracked in the Added state. When the SaveChanges method is called, Entity Framework Core resolves the type passed in to the Add method and generates the appropriate SQL to ensure that the entity is added to the correct table in the database. If you pass in an object graph, any entities that aren't already being tracked will be tracked in the Added state. In the next example, INSERT statements will be generated for the author and all of the books:

var author = new Author
{
    FirstName = "William",
    LastName = "Shakespeare",
    Books = new List<Book>
    {
        new Book { Title = "Hamlet"},
        new Book { Title = "Othello" },
        new Book { Title = "MacBeth" }
    }
};
context.Add(author);
context.SaveChanges();

All of the entities are added in the previous example by virtue of the relationship between them. If you want to add multiple unrelated objects, you can use one of two version of the new AddRange methods. One takes a collection of the same type of object:

var books = new List<Book> {
    new Book { Title = "It" },
    new Book { Title = "Carrie" },
    new Book { Title = "Misery" }
};
context.AddRange(books);
context.SaveChanges();

The other takes a params array of objects:

var book = new Book { Title = "It" };
var product = new Product { ProductName = "Sugar" };
var comment = new Comment { Content = "Hello World" };
context.AddRange(book, product, comment);
context.SaveChanges();

Entity Framework Core is able to resolve the different types passed in to this method and generate the appropriate SQL for each one.

Removing Data

The Remove method is provided for deleting data. Here's an example that uses a stub to represent the entity to be deleted:

var author = new Author { AuthorId = 1 };
context.Remove(author);
context.SaveChanges();

Updating Data

As with previous versions of Entity Framework, if you modify any of the properties of an entity that is being tracked, its state will be set to Modified and an UPDATE statement will be generated when SaveChanges is called. In disconnected scenarios, you had to use the Attach method to get the context to start tracking an entity and then explicitly set its state to Modified to ensure that the UPDATE statement is generated when working with earlier versions of Entity Framework. A new method: Update has been introduced in Entity Framework Core to cater for disconnected scenarios. The next example illustrates a simple service method that receives an entity from somewhere else - serialized from JSON in a Web API end point, perhaps. It is assumed to have been modified in some way:

public void Save(Author author)
{
    context.Update(author);
    context.SaveChanges();
}

The Update method ensures that the entity's state is set to Modified, and SQL will be generated to update all of the entity's properties to the current values. It is a shortcut to using Attach and setting state explicitly. The Update method is also available on the DbSet property.

Summary

This article illustrates the new CUD methods that have been added to the DbContext class in Entity Framework Core. As well as making a nicer API, these methods aid cleaner reusable code creation, since you no longer have to involve the DbSet type when performing CUD operations.

See more about Entity Framework Core at Learn Entity Framework Core.

You might also like...

Date Posted:
Last Updated:
Posted by:
Total Views to date: 1738

0 Comments

Recent Comments

Sivu 19/10/2016 08:21
In response to Entity Framework Core TrackGraph For Disconnected Data
Oh that's very very very nice ! Thanks for the write up Mike, much appreciated for the taking the to...

Mark 12/10/2016 16:42
In response to ASP.NET Web Pages vNext or Razor Pages
Although "Web Pages" was removed from the roadmap, has it just been renamed to "Razor Pages"?...

Satyabrata 12/10/2016 09:20
In response to Entity Framework Core TrackGraph For Disconnected Data
Nice article. Please write more articles featuring ASP.Net web pages. Thank you...

Julian 26/09/2016 14:27
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Fantastic, many thanks Mike! Had got half way down this road before finding your article - saved...

Abolfazl Roshanzamir 14/09/2016 05:36
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Nice article. Thanke you so much ....

cyrus 02/09/2016 15:12
In response to ASP.NET Web Pages vNext or Razor Pages
I've got some news. As Damian stated in this link: https://github.com/aspnet/Mvc/issues/5208 “We...

Simon 01/09/2016 08:00
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Thanks Mike, nice post and exactly what I was looking for. Like you said, I think I'll opt to the...

dave 20/08/2016 14:57
In response to ASP.NET Web Pages vNext or Razor Pages
Do SimplemembershipProvider in viewpages is supported?...

Steven 18/08/2016 04:40
In response to Entity Framework Code First and Stored Procedures
Can you provide the directives (using statements) you're using for EF7 example?...

yousaid 17/08/2016 22:08
In response to ASP.NET Web Pages vNext or Razor Pages
Increasingly, learning a Microsoft tool is no longer worth the return on investment. Too many tools...