EF Core Update: Mastering Data Operations for Beginners

Entity Framework Core: Mastering Data Operations for Beginners

Introduction

Entity Framework Core (EF Core) is a popular Object-Relational Mapping tool for .NET developers. It simplifies database interactions by allowing developers to conceptualize data as objects and properties, using a Code First approach. It is free and open-source. EF Core simplifies data operations, like add, update, and delete entities, with just a few lines of code. It is crucial for new developers to understand these operations when mastering EF Core.

Adding New Entities

Ultimately, a dynamic application is defined by its ability to incorporate new data into your database. In EF Core, this capability is realized through the addition of new entities to your context. Each entity corresponds to a row in a database table, so when you add a new entity, it’s equivalent to inserting a new record into the table.

Adding a Single Entity

To begin, let’s add a single entity to our database. Consider a Post entity in a blogging application:

public class Post
{
    public int Id { get; set; }
    public DateTime DatePublish { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
}

Adding a new Post entity involves creating an instance of this class and using EF Core’s DbContext to track and save it:

using (var context = new BloggingContext())
{
    var post = new Post {
	    DatePublish = DateTime.Now,
	    Title = "EF Core for Beginners", 
	    Content = "This is a sample blog post." 
	   };
    context.Posts.Add(post);
    context.SaveChanges();
}

Here, context.Posts.Add(post); tells EF Core to track the new Post entity. Calling context.SaveChanges(); persists the changes to the database.

Adding Multiple Entities

In addition, it is just as easy to add several entities at once. This can minimize the number of database roundtrips, which is beneficial to the performance.

using (var context = new BloggingContext())
{
    context.Posts.AddRange(
	    new Post { DatePublish = DateTime.Now, Title = "Post First", Content = "Content 1" },
	    new Post { DatePublish = DateTime.Now, Title = "Post Second", Content = "Content 2" }
    );

    context.SaveChanges();
}

Understanding SaveChanges()

The most important method in EF Core is SaveChanges(). This method applies all changes in the tracked entities to the database. For non-blocking saving, the SaveChangesAsync() method should be used for all asynchronous operations, which is especially critical in web applications.

await context.SaveChangesAsync();

Updating Existing Entities

Updating entities in EF Core is also taken care of by the DbContext. When you make a modification to the properties of your entities, the framework monitors those modifications and then applies them to the database when you call SaveChanges().

Updating an Entity

If you need to change the title of a blog post, start by retrieving the entity and then modify its properties.

using (var context = new BloggingContext())
{
    var post = context.Posts.Find(1); // Assuming the post with Id 1 exists
    post.Title = "Updated EF Core for Beginners";
    context.SaveChanges();
}

When SaveChanges() is called, the changes on the post entity are detected automatically by EF Core, and the relevant record is updated.

Updating Multiple Entities

You can loop through the multiple entities to make the necessary updates.

using (var context = new BloggingContext())
{
    var postsToUpdate = context.Posts.Where(b => b.Title.Contains("EF Core"));
    foreach (var post in postsToUpdate)
    {
        post.Title += " - Updated";
    }
    context.SaveChanges();
}

Handling Conflicts and Optimistic Concurrency

Optimistic concurrency control is utilized by EF Core to manage conflicts arising when several processes aim to update the same record. It’s feasible to configure EF Core for automatic entity versioning, or alternatively, conflicts can be manually managed through code to ensure the integrity of data.

try
{
    context.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
    // Handle the concurrency conflict
}

Deleting Entities

In EF Core, deleting entities involves first removing them from the DbContext and then capturing the untracked changes in the database.

Deleting a Single Entity

How to delete an entity is shown in the following code snippet:

using (var context = new BloggingContext())
{
    var post = context.Posts.Find(1); // Assuming the post exists
    context.Posts.Remove(post);
    context.SaveChanges();
}

Bulk Deletion and Performance Considerations

Finally, for deleting several entities, as with adding or updating, RemoveRange can be applied.

using (var context = new BloggingContext())
{
    var postsToDelete = context.Posts.Where(b => b.Title.Contains("Delete"));
    context.Posts.RemoveRange(postsToDelete);
    context.SaveChanges();
}

Handling Concurrency Conflicts

Similarly, deletions may suffer from concurrency conflicts and can behave unexpectedly if the entity has been updated or deleted after it has been obtained.

try
{
    context.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
    // Handle the concurrency conflict
}

Conclusion

Understanding the operations of adding, updating, and deleting entities in Entity Framework Core is a core competency for every .NET developer developing interactive and data-driven apps. This guide has covered how you can modify data using EF Core. By working on these practical examples and incorporating them into your projects, you’ll get a better grasp of EF Core’s functionality and how to apply its features effectively. As you grow more adept at these operations, delve into more advanced EF Core features and best practices to further enhance your applications. Good luck with your coding journey!

Leave a Reply

Your email address will not be published. Required fields are marked *