Introduction

In this article, I will walk you through a simple application using MVC4 and Entity Framework 5 and will demonstrate how one can make use of code first technology. I will be using MvsScaffold for quick creation of controllers and views. We will be creating a TODO application.

Prerequisites

Visual Studio 2010 with SP1

MVC 4

Nuget Package manger for Visual Studio

SqlExpress database

Background

Code first – Code First enables you to describe a model by using C# or Visual Basic .NET classes. Code First is a new development
methodology available beginning with the Entity Framework 4.1. You can use Code First to generate a new database from a model, or map your model to an existing database.
You can read more here.

Entity Framework - Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using
domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write. You can learn more about
this here.

MVC 4 – Successor of MVC3, ASP.NET MVC 4 is a framework for building scalable, standards-based web applications using well-established design patterns
and the power of ASP.NET and the .NET Framework. Find all the related information here.

MVC Scaffolding – This is a Scaffolding package for ASP.NET which is installed via NuGet using ‘Install-Package MvcScaffolding’ command.
Thanks to Scott Hanselman and Steven Anderson.

Quick Preparation

Before we start, lets make sure you have NuGet package manager and SQL component if you don’t already have it.

Click on the ‘Online Gallery’ in search box type NuGet and hit enter. It will show the NuGet Pakage Manager, I already have it installed to you can see the green click mark. If you do not have install, double click it to install, and follow the instructions.

When you have the NuGet pakage install, you should be able to see the library package manager. Tools-> Library Package Manager –> Package Manager Console

Notice line 5 and 9, where I am modifying the
ModifiedOn and CreatedOn before saving and updating the model.

Update: Adding some information about line 10 as per a user commentLine 10: context.Entry(task).State = EntityState.Modified; This is a way to tell the dbContext that some properties of the entity has been modified but SaveChanges() is not called. Entity framework takes care of updating the entity with the modified values. Calling the context.Entry() returns DbEntityEntry<TEntity> object which provide access to information about and control of entities that are being tracked by the DbContext. In a simple words, it's the way to tell Entity Framework to update an entity with the modified values.

You would also need to have following line in _CreateOrEdit.cshtml of tasks so persist the values of
CreatedOn.

1: @Html.HiddenFor(m=>m.CreatedOn)

Run the application again and you should be able to add, update and delete the data

This is not it, this has automatically created the database for you, you can check that out, Browse to SQLExpress database there you should be able to see a database for this application.

Check the Tables, Columns, Primary Keys and Foreign Keys they are all in place exactly as you created them in the models.

There is too much explain, however, as per the scope of this article, consider this article as starting point to plunge deep into this. Before I wrap up this article,
one last thing want to inform you about which is called database initializer.

Go to TODOContext.cs in the Model folder, create a constructor of
TODOContext as follows:

It does as the name says DropCreateDatabaseIfModelChanges when you change any Model by adding or deleting some properties, the current database will be dropped and it will be recreated. If you modify the model without having this constructor, you might see an error as follows

I have already mentioned the database will be created in the SQLExpress, do not be surprised if you do not see the database getting created in the database specified by you in the connectionstring of the web.config.

Note: Entity framework will always try to connect to the local SQL Server Express database (.\SQLEXPRESS). Starting with EF 5,
Ef will use LocalDb if it doesn’t detect SQL Express running. SQL Express will always get precedence if it is installed, even if you are using Visual Studio 2012.

Share

About the Author

I am just as good as I get; Otherwise, I am a Software Professional with years of Software Development Experience and my USP is that I believe in bestowing excellence in the software solutions that are in tune with the user requirements and deliver the excellent results to the clients. I present myself as an innovative professional who utilize the unique blend of technical expertise with business acumen.

The term 'Scaffold' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included,
verify that the path is correct and try again.
At line:1 char:9
+ Scaffold <<<< Controller Case -Repository
+ CategoryInfo : ObjectNotFound: (Scaffold:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

Tried out Solutions.
removed and reinstalled the MVCScaffold then restarted Visual Studio.
Also , checked the respective packages folder in Visual Studio which is present.

I have solved this problem. Additionally, I think it's a bug. So, I searched about this error on the web and I found a solution. Then I have changed my regional settings to English, the problem solved.

I created my app to completion, and by running the app, it creates the database for me, as expected. Now, when I deploy this to production, what code changes do I need to make in order for the app to permanently use the database I have set up in production rather than creating a local one to use on the fly?

Not sure what exactly you mean by "My Dir". Whose directories are those where the files are getting generated ? . Well, I guess you want to know how to generate the files for every model by one command. I didn't explore various options provided by MVCScaffolding, however, since you are doing it from PowerShell you can anytime use the power of it.

If I were you, I would explain more detail about this line. How it works and why it is done this way, and why we don't have any .UpdateDbContext or something when we make a change, and what is with this entitystate.modified, what does it mean and why do we need to do that?

10: context.Entry(task).State = EntityState.Modified;

You should always describe code that isn't explicitly obvious, especially when you are doing a beginners tutorial, apart from at, great work.

Also, why no foreginkey association or data annotation on the NoteId field like you have on the other FK data annotations field?