C# MVC With Entity Framework - Hello World Example

Do you like this?

Summary:
This post shows you the key steps in creating your first project using C# with MVC and Entity Framework.


Content:

Step 1: Create a new MVC Project in Visual Studio.
Step 2: When it asks for project template, you can select Empty since you are learning, it's better to show you how to create everything from scratch.
Step 3: If you run the application, you will see only the error HTTP 404 because there is no controller that can handle this request at the moment.
Step 4: Right click on Controllers folder to add a controller.
Step 5: Select Empty MVC Controller as the template. Let's name the new controller as HomeController
Step 6: If you run the application, it will show errors because the default URL for any controllers will be "{controller}/{action}/{id}". So to navigate to our HomeController, we need to access the page at /Home/Index. However, if you access that page now, it will also show errors because we haven't got the View files set up.
Step 7: To change the routing behaviours, let's open RouteConfig.cs under App_Start folder.
Step 8: Change the code as follows:


//-----------OLD CODE-------------------------
//routes.MapRoute(
//    name: "Default",
//    url: "{controller}/{action}/{id}",
//    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
//);
//-----------END: OLD CODE-------------------------

routes.MapRoute(
	name: "Default",
	url: "",
	defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Step 9: Run the application and open the Root homepage. It will show errors because we have no view files. However, you can see that the page is handled by HomeController now.
Step 10: Open the HomeController.cs file. Right click on the Index method and select Add View. It will automatically create the file Index.cshtml under Views/Home folder
Step 11: Run the application again and it should show you the Index page now. You can also modify the content of Index.cshtml under folder Views/Home. When you refresh the browser, it should immediately show the changes.
Step 12: If you want to use layouts for your webpages, you can create a Layouts folder and then create cshtml files there. Let's create _LayoutPage.cshtml under Layouts folder. Below is its content:
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <h1>THIS IS A TESTING SAMPLE OF MVC 4</h1>
    <div>
        @RenderBody()
    </div>
</body>
</html>
Step 13: To use the layout page, let's open the Index.cshtml of Home controller and insert the following content:
@{
    ViewBag.Title = "HomePage";
    
}

This is a test
You might notice that we didn't mention the layout page but the server can still recognise is. The reason is that _LayoutPage.cshtml is a special file name. If you create the file, it will be used as the default template.
Step 14: If you want to use a different layout, create your own layouts and in the view files which the template is used for, you should add this line:
@{
    ViewBag.Title = "The Title";
    Layout = "~/Views/Layouts/_Other_Layout_Page.cshtml";
}
Step 15: Let's assume we have set up the database with only one table Author that consists of columns ID and Name. We now want to create controllers that can interact with the tables in the database using Entity framework. First, you need to add Entity framework using Nuget.
Step 16: Open Web.config and edit as follows:
<connectionStrings>
	<add name="DatabaseContext" providerName="System.Data.SqlClient" connectionString="Server=localhost\sqlexpress;Database=your_database;User ID=your_username;Password=your_password;" />
</connectionStrings>
Step 17: Visual Studio can create scaffolds for controllers that use Entity to connect to database. First, you have to create the model. Let's create Author.cs file under Models folder.
public class Author
{
	public int id { get; set; }
	public string name { get; set; }
}

public class AuthorContext: DbContext {
	public AuthorContext(): base("DatabaseContext"){}
	public DbSet authors { get; set; }
}
Step 18: Right click on Controllers folder to add a new controller. Under Template, choose MVC Controller with Read/Write actions and views, using Entity framework. Select the classes for the model and data context. Visual Studio will automatically add a new controller, AuthorController, and a new folder Author under Views folder with Index.cshtml, Create.cshtml, etc.
Step 19: If you run the application now, it might give you errors when you try to access localhost/Author/Index. The reason is that the generated view files for AuthorController uses @Scripts. Hence, you need to add Microsoft.AspNet.Web.Optimization using Nuget and to add the following line at the top of the pages:
@using System.Web.Optimization
And in Web.config, add this line:
<add namespace="System.Web.Optimization" />
Step 20: After adding, your project should be able to run smoothly now and it is capable of adding, removing and editing Author table in the database when you access localhost/Author/Index

 
comments powered by Disqus