Thursday, 3 March 2016

Entity Framework with asp.net MVC


In this blog I am going to show how we can  check whether  particular details are present in the SQL-server database using Entity framework from an asp.net MVC application.
Step 1:
Create a ASP.NET MVC Application
            1) Open Visual Studio
            2)Select File->New->Project
            and select ASP.NET Web Application under Visual C# template in the Left panel.

            3) Give the Project Name as SampleEFProject then Click OK

            4)From the popup window Select  Empty Template and check the below checkbox MVC
                and click ok.
Now our MVC Sample Project is created .
Step2:
1)Right click on the References and select Manage NuGet Packages.

2)Now NuGet Package Manager will be displayed
3)Then click on the browse part of the NuGet Package Manager and Search EntityFramework
4)Now you can see an entity Framework package install it. Before installing it will show some confirmation &  Acceptation  messages accept all messages.

5)Now check reference section of your project there you can see new references


EntityFramework and  EntityFramework.SqlServer
6)Now check your Web.Config file there you can see a portion like below
<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
7)If it is not there in your Web.Config then add the above portion to your Web.Config

Step3:

Create a Class Library in the same solution
1)Right Click on the solution Explorer
2)Then click Add->New Project and then Select Class Library from the list and give class Library name as IntegrationWithEF.


3)Now you can see a class library is created in your project with Name IntegrationWithEF.

4)Now Add Entity FrameWork Reference to this class library also .
We can follow the same steps that we did for MVC Project for the same.
5)So right click on the Class Library Reference -> Select Manage NuGet Packages
Then browse for Entity FrameWork , find it and install it.
Step4:
Create a SQL-SERVER database with name LoginManagement
you can use the following query to do that
create Database LoginManagement

Then create a table with name Login and fields ID,Username and Password
We can use the following query to do the same
USE [LoginManagement]
GO


SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Login](
            [ID] [int] NOT NULL,
            [Username] [nvarchar](50) NULL,
            [Password] [nvarchar](50) NULL,
           
PRIMARY KEY CLUSTERED
(
            [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Then insert some values in to it.

insert into Login values(1,'arun','prasanth')


Now our Database part is over . Again come back to Visual Studio .

Step5:

1)Right Click on the Class Library Project and Select Add->New Item



2)Select ADO.NET Entity Data Model and give name as TestingIntegration and click Add Button


3)Select EF Designer from data from the window and click Next


4)Click on the new connection from the box.


5) Click on Change button in the new window 


6)select DataSource -SQL Server and click ok

7)Fill your SQL server Credentials and Click Test Connection


Note : In this example I am using Windows Authentication, If you want then you can use Sql server authentication too.

If the test connection is succeed then click ok .

8) Click next button in the window.

Note : If you are selected Sql server Authentication then you need to Check the radio buttion "Yes , include sensitive data in the connection string " part in the dialog window. Then click on next and select Enity Framework 6.x and click next .


9) Now we can see one window it shows Details of our Database. Select our table from that and click finish.


Step6:

Open class.cs file in your Class Library and replace the context with following

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IntegrationWithEF
{
    public class Integration
    {
        public int GetLoginInfo(string Username, string Password)
        {

            LoginManagementEntities obj = new LoginManagementEntities();
            var Result = obj.Logins.Any(z => z.Username == Username && z.Password == Password);
            if (Result)
            {
                return 1;
            }
                        else {
                return 0;
            }        }
    }
}
Then open App.Config file in your Class library
and find connectionStrings tag and copy that

in my case it is like following , In your case it will be different So copy that

<connectionStrings>
    <add name="LoginManagementEntities" connectionString="metadata=res://*/TestingIntegration.csdl|res://*/TestingIntegration.ssdl|res://*/TestingIntegration.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=ARUN\SQLEXPRESS;initial catalog=LoginManagement;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>

and include it  in your Web.Config file of SampleEFProject 


Step 7 :

Add the Class Library " IntegrationWithEF" as Reference to our MVC Project

1) Right Click on References -> Then Select IntegrationWithEF

 Step 8 :


Create a New controller with name LoginController

And replace its content with below .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IntegrationWithEF;//including Class Library Namespace

namespace SampleEFProject.Controllers
{
    public class LoginController : Controller
    {
        // GET: Login
        public ActionResult Index()
        {
            Integration obj = new Integration();
          int Result=  obj.GetLoginInfo("arun","prasanth");

            return View();
        }
    }
}

Then Open your RouteConfig.cs file in MVC Project  and replace the content with below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace SampleEFProject
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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



Step 9:
Fix a break point on your login controller in the below line
int Result=  obj.GetLoginInfo("arun","prasanth");

Then  run  the project, You can see the results . In our databse we have the data show it will return 1 as result .

Note : 

  • This is a small program that introduce very basics of entity framework using MVC
  •  We can elaborate it more. We can use many tables , many fields Big Queries, Procedures in EF.
  • In this project we did not create any Views and Model classes so if you want to use the results in the view then create a view and model class then bind the results to the model and use it.













No comments:

Post a Comment