Just about every web application is going to want to store data at some point.
In our case, we want to save posted auction so that other users can view and bid on them.
Luckily, Microsoft's Entity Framework Code-First data access layer makes this incredibly easy to do.
What's more, Visual Studio includes it for us in the ASP.NET MVC template.
The first thing you'll need to do in order to interact with the database using Entity
Framework Code First is to tell it about your model by creating what's known as a database context.
In practice, this is nothing more than a class that extends the Entity Framework DbContext
base class, and provides any number of properties describing the entities that you will be persisting to the database.
So we'll begin by creating one of these DbContext classes in our models folder.
We'll name it AuctionsDataContext.
Then we'll have it derived from the System.Data.Entity.DbContext class.
Now we'll tell Entity Framework about the properties that we'd like to persist to the
database by exposing them in the form of properties on the data context that use the generic DbSet datatype.
For example, we'll want to save auctions to our database, so we'll add an auctions property
to our data context like this. And it's as simple as that.
Now we can begin using our database context to interact with the database.
To show the context in action let's overhaul our Auctions controller that has been littered
with hard-coded auctions up to this point.
We'll replace those hard-coded auctions with references to our new data context like this
one that saves a new auction to the database.
Here I'm creating a new instance of the AuctionsDataContext, then I'm adding my instance of an auction
to the Auctions collection in that data context.
Finally, I'm calling the SaveChanges method to save those changes to the database.
Before we're ready to run this code there is one more thing I have to do.
Depending on your system's configuration the site may or may not execute as we currently have it.
This is because Entity Framework is pretty smart, and it tries to find the best way to
create and access a database depending on the software that you have installed on your machine.
To avoid this, we'll explicitly tell Entity Framework to use the technology called SQL
Express LocalDB that was installed as part of Visual Studio.
And will do this by adding a connection string to our Web.Config.
To begin, open up your Web.Config file and find the connectionStrings section.
There were already be a connection string here that Visual Studio added for us, which
tells Entity Framework where to find our membership database.
This is just what we want to do for our database as well.
So go ahead and make a copy of this connection string.
Then replace any references to the ASP.NET membership database with a new database name.
I'm using MvcAuction.Models.AuctionsDataContext the name of our data context.
Likewise change the name of the connection string to MvcAuction.Models.AuctionsDataContext.
This name is very important because it matches the full class name of our data context, a
convention that Entity Framework uses to locate the appropriate connection string for each data context.
Finally, remove the initial catalog property, we're not going to be needing it.
With this code in place go ahead and visit the Create page and try to add a new auction.
By default, when you first attempt to read from or write to a DbContext Entity Framework
will examine the model you've provided and automatically generate a database schema based on that model.
Entity Framework will also check to make sure that the database exists, and if it doesn't,
Entity Framework will go ahead and create it for you.
In order to do all this, however, Entity Framework requires a few things, most notably it requires
a property that will serve as the Entity's primary key.
Luckily, Entity Framework offers conventions that make this easy just make sure the entity
you're trying to save has a property name Id or use the Key Data Annotation attribute
to specify another property that will serve as the primary key.
Luckily, our auction model already has this property, so we don't need to add the Data Annotation.
Note that before it saves anything to the database, Entity Framework guards against
invalid data by using the data annotations that we applied in the previous video to validate the model.
If it finds any properties with invalid values Entity Framework will refuse to save the entity
and throw an exception instead.
If you're able to post your auction without raising any exceptions, you can assume that
your auction has been saved to the database.
The problem is we don't currently have any way of knowing for sure since our index action
is still displaying a list of hard-coded auctions.
So let's go ahead and take care of that right now.
We'll start by removing the hard-coded auctions, and then we'll retrieve the auctions from the database instead.
Notice how I'm calling the ToArray method on the Auctions property.
This tells Entity Framework to go ahead and execute the SQL call at this point, otherwise
the SQL call might get delayed until the view runs.
At that point the data context that we've created here will probably be out of scope,
and we won't be able to reference it anymore.
Using the ToArray method here we're sure to get the collection of auctions and then we
can pass them to the view.
Likewise, let's update the Auction action so that it can view the full details of an
individual auction that we retrieved from the database.
Here I'm using the Find method to find an auction by its primary key, in this case, the Auctions ID.
With these changes in place we should be able to run the site and see the auctions that
we've added to the database.
You should also be able to navigate to the Auction action and pass it the ID of an Auction
that you'd like to view.
One last thing you'll need to know about Entity Framework before we move on is that it's get
pretty upset when you change the model after the database has been created.
In order to avoid this you've got two options, first, you can use Entity Framework's Code
First Migrations feature, which keeps a history of the changes to the model as you make them,
giving Entity Framework the information it needs to keep the corresponding database schema up to date.
Though this is the preferred option, it is beyond the scope of this course so we'll not
be covering it here.
The second option is to apply one of Entity Framework's database initializers or classes
that instruct Entity Framework about how to initialize the database.
Entity Framework includes two initializers out of the box, the DropCreateDatabaseIfModelChanges
initializer and the DropCreateDatabaseAlways initializer.
As their names imply, these two initializers drop and re-create the database either when
the model changes or whenever the web application is restarted.
Once you've chosen the database initializer you'd like to use, simply execute the Database.SetInitializer
command to apply it.
Here I'm setting the database initializer in the static constructor of the AuctionsDataContext.
This is to make sure that I never use this data context without the initializer getting set.
With this database initializer in place, I'm now free to change the model however I like,
and Entity Framework will regenerate the database for me every time.
It's very important to realize that dropping and re-creating the database means that any
data that's in the database will be lost, so you're not going to want to use these initializers
in a production environment.
To support a production environment release you're going to want to switch to the Entity
Framework Code First Migrations option that I mentioned earlier.
Database initializers, however, are a great option for enabling rapid prototyping in the
early phases of development.
In this video, I showed you how to take all of that data that we've been posting over
the past few videos and use the Entity Framework to quickly and easily persist it to a database.
I even showed Entity Framework's built-in mechanisms for validating the data before it's persisted.
And that concludes this chapter of working with data in ASP.Net MVC websites.
With the techniques I've shown here you should be able to receive data from the user and save it to a database.