In this chapter, we created our first Entity Framework-based application. We started by creating a new console application .NET project. We then added the Entity Framework reference using NuGet. Then, we decided what data we wanted to store in the database and created a class that maps to a table in the database, that is, the Person
class. Then, we created our database abstraction, the Context
class, inheriting from DbContext
. We specified the desired connection string in its constructor and added this connection string to the application configuration file. Then, we added a single property to our context, People
, which was a collection of Persons
object, of the type DbSet
of Person
. At this point, we ran our application. We observed that a database was created with a single table, based on the this property. The database creation process used many conventions, including the table name and making the PersonId
column unique (by identity)
and primary key.
We then worked on adding a row to the preceding table. We created an instance of the Person
class, setting some properties on it at the same time. We created an instance of Context
, following the IDisposable
pattern. We then added the instance of Person
to the collection specified by the People
property of Context
using the Add
method. Finally, we called SaveChanges
to commit our in-memory objects to the database, thus making them rows in the Person
table. Updating the inserted data was easy, as well. We queried the rows from the database by enumerating the objects inside the People
property of Context
. We picked a row, changed its properties, and called SaveChanges
to update the data. Deletion was done using the Find
method instead of enumerating a query, and then marking the object for deletion by calling Remove
method of DbSet
and calling SaveChanges
yet again, thus deleting the data from the database. We finished the chapter by mentioning that Entity Framework has many ways to perform some actions, and this includes CRUD operations. We will see other ways to archive these tasks in subsequent chapters. Congratulations on getting your first app working!
18.220.202.209