Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Thursday, May 23, 2013

How to access an Existing Database Using Entity Framework 5.0 Code-First

In my previous two articles we see how to use Entity Framework Code First and mvcscaffolding in asp.net mvc4. We didn't create any database into above articles. Database was created automatically from model class. But in this article I’ll explain how to use existing database in an EF code-first application. For this purpose we’ll make two small changes in any asp.net mvc code-first project.

1. Define connectionstring in web.config for existing database.

<connectionStrings>
    <add name="DonarConnectionString" connectionString="Data Source=MSSQLSERVER;initial catalog=BloodDonar;user id=sa;password=;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
  </connectionStrings>

2. In previous two articles we have created a database context class which is inherited from “DbContext”. Now we need a constructor for this class. Notice, in this constructor, that we call into the base constructor and pass it a string.  This is the connectionstring which is created in previous step. EF will use it during database connections.

        public InventoryContext(): base("name=DonarConnectionString")
        {
            Database.SetInitializer<MvcApplication2Context>(null);
        }

Here, we are setting the Initializer for the context to null with SetInitializer<>.  So, EF will not try to change any database initialization logic.
Read More

Monday, April 29, 2013

Asp.net MVC Scaffolding in code first scenarios


In this article we will walk through the creation of a read/write/update/delete of Recipes and its related (many) Ingredients using MvcScaffolding and MVC 4.

MVC Scaffolding gives you a fast way to get some helpful, effective code, that you can then edit and adapt according to your needs.


In other words, MvcScaffolding  can create automatically:
1. Controllers for creating, viewing, updating and deleting instances of your model,
2. Corresponding Views for creating, viewing, updating, and deleting data,
3. Database contexts from your model,
4. Catalyze the creation of a database model including support for one-to-many relationships and more…

In this article we'll create a blood donar application using MVC Scaffolding and code first.

Let’s create two models for blood group and donar. Add the following classes to our Models folder, then compile the solution :

BloodGroup.cs

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace Blood_Donar.Models
{
 public class bloodgroup
{
public int bloodgroupid { get; set; }

[DisplayName ("Blood Group")]
public string name { get; set; }

}
}


Donar.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Blood_Donar.Models
{
public class donar
{
public int ID { get; set; }

[DisplayName ("Donar Name")]
[Required(ErrorMessage="Name is required")]
public string Name { get; set; }

public string Address { get; set; }

[Required(ErrorMessage="Mobile no is required.")]
public int Mobile { get; set; }

[DisplayName ("Blood Group")]
public int bloodgroupid { get; set; }

public virtual bloodgroup bloodgroups { get; set; }

}
}

Execute following command into Package Manager Console:
1. Install-Package EntityFramework
2. Install-Package mvcscaffolding

Next, we will create a complete Create-Read-Update-Delete (CRUD) UI for those models by executing a single command into Package Manager Console:



Scaffold Controller Donar

This command will create a database context,  a controller, and all the views for Create-Read-Update-Delete (CRUD) actions. Right now you can run it (Shift-F5).

If you have SQL Server Express running on your machine, EFCodeFirst will automatically connect to it, create your database schema, and you’ve got a basic working application without writing a single line of procedural code. Also you can add a SQL Server Compact to your project by issuing the following command in the Package Manager Console:

Install-Package EFCodeFirst.SqlServerCompact

Again, execute following command for BloodGroup model

Scaffold Controller BloodGroup

To create repositary class execute following command into package manager console

Scaffold Controller Donar –Repository -Force

Now the scaffolder will produce two additional class, Donar Repository, and the following interface which Donar Repository implements:

public interface IdonarRepository
{
IQueryable<donar> All { get; }
IQueryable<donar> AllIncluding(params Expression<Func<donar, object>>[] includeProperties);
donar Find(int id);
void InsertOrUpdate(donar donar);
void Delete(int id);
void Save();
}

Follow same process for Bloodgroup.

Now run the application and see the magic of MVCScaffolding.

Read More

Wednesday, April 24, 2013

Create an application using asp.net MVC 4 and EF code first

In this tutorial we will create our first MVC application using visual studio 2012, MVC 4 and EntityFramework Code First.

Step-1: Create Project
1. In Visual Studio 2012, add a new project by selecting the File menu, then New and then Project.
2. Select ASP.NET MVC 4 Web Application and C# as a language of choice.
3. Name the project Inventory and then click OK.
4. In the New ASP.NET MVC 4 Project wizard, choose Internet Application and razor view engine.
5. Leave the default values of the other options and click OK.

Step-2: Create a model class
1. In Solution Explorer, right click the Models folder.
2. Select Add from the menu and then from the bottom of its context menu choose Class.
3. In the Add New Item dialog, change the new class name to Category.
4. A new file, Category will be created.

Add following code into category class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;

namespace Inventory.Models
{
    public class Category
    {
        public int CategoryID { get; set; }

        [DisplayName("Category Name")]
        public string CategoryName { get; set; }
    }
}

Now, We’ll create a class that inherits from DbContext and knows how to serve up and manage the Category object. The Entity Framework will take care of bridging the classe and a database. Before the use of DbContext, we’ll need to create a reference to the Entity Framework API. This is the assembly that contains the Code First runtime. Visual studio 2012 automatically creates a reference of Entity Frmework. But for VS 2008 or 2010 we need to create a reference of EF by using Nuget. Nuget allows us to easily find and install reference assemblies from the internet.

1. Select the Inventory project in Solution Explorer.
2. From the Tools Menu, choose Library Package Manager which has a sub-menu.
3. From the sub-menu choose Package Manager Console.
4. At the console’s PM prompt type install-package EntityFramework then hit enter.
When the package is installed, you should see the “success message”.

Add following class to the Models folder and compile the application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace Inventory.Models
{
    public class InventoryContext: DbContext
    {
        public DbSet<Category> Categories { get; set; }
    }
}

Step-3: Create Controller
1. Build the project by choosing Build from the Visual Studio menu and then Build Inventory from its drop-down menu.
2. In the Solution Explorer, right click the Controllers folder.
3. Click Add from its context menu and then Controller.
4. In the Add Controller window, change the Controller Name to CategoryController and select MVC Controller with read/write and view using EntityFramework.
5. Select Model Class: Category(Inventory.Models).
6. Select DBContext Class: InventoryContext.Models).
7. Views: Razor(cshtml).
Click the Add button.
The CategoryController class will be created with ActionResult methods: Index, Details, Create, Edit and Delete.

Step-4: Change the global.asax
1. Open the global.asax file from Solution Explorer.
2. Modify the MapRoute call to change the value of controller from “Home” to “Category”.
 routes.MapRoute(
   "Default", // Route name
   "{controller}/{action}/{id}", // URL with parameters
   new { controller = "Category", action = "Index", id = UrlParameter.Optional }

Our first application is created. Run the application. The CategoryController.Index action will be the first method called.

Read More

Wednesday, April 17, 2013

Introduction to MVC Concepts


The intension of MVC or Model-View-Controller is to build applications in a modular way. In MVC, 3 general parts/layers are responsible for creating the output and allowing the interaction with the user:

1.Model

2.View

3.Controller


Model:

In the context of the MVC the model has the data that is essential to render things in the view. So it represents the data that are mandatory for rendering. It also takes over the process related to the domain. The model is used to do something and get the data.

View:

A view takes care of “rendering the pixels on the screen“and should be as dump as possible. Naturally a view class understands one or more model(s) and outputs the information of that model. (A view is not allowed to write in the model.) So the view is conscious of the model and knows how to read the data out of it – but never the model should know something about the view!

Controller:

It glues together Model and View, it controls the user communication with the model and the view. (It’s a thin layer that connects models with their views)

The diagram below illustrates a common request cycle in an MVC application.


The process begins when a user takes an action on a web page – submitting a form that adds a new blog post, for example. The request is sent to the blog controller, which extracts the data submitted via the HTTP POST request and sends a message to the blog model to save a new post with this data.

The model checks the data against its validation rules. Assuming it passes validation; the model stores the data for this new post in the database and tells the controller it was successful. The controller then sets a variable for the view indicating success.

Finally, the view displays this message to the user back on the web page, and they know their new blog post has been successfully created. If, for some reason, validation of the data failed, the model would alert the controller of any errors, which would set a variable containing these errors for the view. The view would then present the original form along with the error messages for any fields that didn’t validate.


Read More