Book Image

Code-First Development with Entity Framework

By : Sergey Barskiy
Book Image

Code-First Development with Entity Framework

By: Sergey Barskiy

Overview of this book

<p>Entity Framework Code-First enables developers to read and write data in a relational database system using C# or VB.NET. It is Microsoft's answer to demand for an ORM from .NET developers.</p> <p>This book will help you acquire the necessary skills to program your applications using Entity Framework. You will start with database configuration and learn how to write classes that define the database structure. You will see how LINQ can be used with Entity Framework to give you access to stored data. You will then learn how to use Entity Framework to persist information in a Relational Database Management System. You will also see how you can benefit from writing ORM-based .NET code. Finally, you will learn how Entity Framework can help you to solve database deployment problems using migrations.</p>
Table of Contents (15 chapters)
Code-First Development with Entity Framework
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Deleting data from the database


Interestingly enough, there is a lot of similarity in the approaches we used for updates and deletions. We can use a query to find data and then mark it for deletion by using the Remove method of DbSet. This approach actually has the same drawbacks as it does with the update, resulting in a select query in addition to the delete query. Nonetheless, let's take a look at how it is done:

using (var context = new Context())
{
    var toDelete = context.People.Find(personId);
    toDelete.Phones.ToList().ForEach(phone => context.Phones.Remove(phone));
    context.People.Remove(toDelete);
    context.SaveChanges();
}

This code deletes each child entity, phone in our case, and then deletes the root entity. You would have to know the primary key value for the entity you want to delete. The preceding code assumes that you have this value in the personId variable. In the case of a web application, this value will be submitted to the method that handles deletion. Alternatively...