Pages

Friday, 27 December 2013

Creating a Model using entity framework in MVC

In this article we are going to see how to create a model using entity framework and used it in the Application. Let we take a scenario that the List out the employee information based on the employee id as input.

Sql Script:

CREATETABLE EMPTABLE

(

ID INTIDENTITY(1,1),

NAME VARCHAR(200),

COUNTRY VARCHAR(400),

MARRIED VARCHAR(200)

)

INSERTINTO EMPTABLE(NAME,COUNTRY,MARRIED)

VALUES('RAJESH','INDIA','NO')

INSERTINTO EMPTABLE(NAME,COUNTRY,MARRIED)

VALUES('SURESH','US','NO')

INSERTINTO EMPTABLE(NAME,COUNTRY,MARRIED)

VALUES('KISHORE','US','YES')

INSERTINTO EMPTABLE(NAME,COUNTRY,MARRIED)

VALUES('PREM
KUMAR','UK','NO')

Html:

@model TestingMvc.Models.Employee

@{

ViewBag.Title = "Employee Data";

}

<h2>Employee Information</h2>

<tablestyle="border:2px solid gray">

<tr>

<td><b>ID</b></td><tdstyle="padding:5px">@Model.EmployeeId</td>

</tr>

<tr>

<td><b>Name</b></td><tdstyle="padding:5px">@Model.EmployeeName</td>

</tr>

<tr>

<td><b>Country</b></td><tdstyle="padding:5px">@Model.Country</td>

</tr>

<tr>

<td><b>Married</b></td><tdstyle="padding:5px">@Model.Married</td>

</tr>

</table>

Now we concentrate on Code part:

Create a Model Class for Employee and the parameters and map that with actual name of the table and column with the attributes.

[Table("EMPTABLE")]

publicclassEmployee

{

[Column("ID")]

publicint EmployeeId
{ set; get; }

[Column("NAME")]

publicstring
EmployeeName { set; get;
}

[Column("COUNTRY")]

publicstring Country
{ set; get; }

[Column("MARRIED")]

publicstring Married
{ set; get; }

}

Now create a context for that Employee Model class.

class should be derived from the Dbcontext then add the properites with DbSet Type, which means it take the set of collection values from the Model class Employee

publicclassEmployeeDbContext:DbContext

{

publicDbSet<Employee> Employees { set;
get; }

}

Now add the web.config connection string the name should be same as the context, so at the runtime engine will search for that name in the connection string. Place the connection string in the root web.config.