Wednesday, August 27

MVC application using entity framework with firebird database



Introduction:-
                     MVC application with entity framework and firebird database
Description:-
                     Most of the developer are using entity framework with SQL server database, But when they are switching to other database they are faced lots of issues during their development process.
In this article I have created a sample MVC application which is using entity framework with firebird database. To configure firebird database to use entity framework you have to follow below processes.
Ø  First check you have installed entity framework and EntityFramework.Firebird or not.To check this right click on your reference as below



And click on Manage NuGet Packages it will show you below screen. If you don’t have this option please download and install it in your machine.
Ø  Now search for EntityFramework.Firebird and install it as well.

Now come to our development section.
Here is my sample solution overlook
 
First I have taken one connection string in our root web.config file.
Here is the code
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="StudentContext" connectionString="DataSource=192.168.110.21;User=VONLINE;Password=OmugZug9;Database=E:\SomeFolder\Database.FDB;Port=3050;Dialect=3;Charset=None; Connection lifetime=15;Pooling=true;MinPoolSize=0;MaxPoolSize=50;Packet Size=4096" providerName="FirebirdSql.Data.FirebirdClient" />
  </connectionStrings>
 
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.0"></compilation>
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
 
  <entityFramework>
    <defaultConnectionFactory type="FirebirdSql.Data.EntityFramework6.FbConnectionFactory, EntityFramework.Firebird" />
    <providers>
     
      <provider invariantName="FirebirdSql.Data.FirebirdClient" type="FirebirdSql.Data.EntityFramework6.FbProviderServices, EntityFramework.Firebird" />
    </providers>
  </entityFramework>
  <system.data>
    <DbProviderFactories>
      <remove invariant="FirebirdSql.Data.FirebirdClient" />
      <add name="FirebirdClient Data Provider" invariant="FirebirdSql.Data.FirebirdClient" description=".Net Framework Data Provider for Firebird" type="FirebirdSql.Data.FirebirdClient.FirebirdClientFactory, FirebirdSql.Data.FirebirdClient,  Version=4.5.0.0, Culture=neutral, PublicKeyToken=3750ABCC3150B00C" />
    </DbProviderFactories>
  </system.data>
</configuration>

Now in global.asax file application start method enter the Yellow marked line
   public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            Database.SetInitializer<MySchoolDemoMvcApp.Models.StudentContext>(null);
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }

Now in Model create one class to represent your database table
Here is code for UserData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace MySchoolDemoMvcApp.Models
{
//Table attribute is given because the original table name is USERS where as we have

//declared it as userdata for this you have to import a namespace as

//System.ComponentModel.DataAnnotations.Schema

    [Table("USERS")]
    public class Userdata
    {

//As entity requires a key value ,I have set user-id with key attribute for this you have

// to import System.ComponentModel.DataAnnotations namespace
             [Key]
            public int USER_ID { get; set; }



            public string FULLNAME { get; set; }
            public string USERNAME { get; set; }
      
    }
}

Now we have to establish a connection string to connect with firebird  database. For this I have created a context class inside MODEL.
Here is the StudentContext.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;



namespace MySchoolDemoMvcApp.Models
{
//initialize database connection here
    public class StudentContext:DbContext
    {
        public DbSet<Userdata> userrecords { get; set; }
    }
}

Now I have created one class inside CONTROLLER as SchoolHomeController.cs
Here is the code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MySchoolDemoMvcApp.Models;
using System.Data.Linq;

namespace MySchoolDemoMvcApp.Controllers
{
    public class SchoolHomeController : Controller
    {
        //
        // GET: /SchoolHome/

        public ActionResult name()
        {
              ViewData["myname"]=new List<string>() {
            "raja","shibuna"
           
            };

              return View();
        }

        public ActionResult StudentDeatils()
        {
            List<Student> obj = new List<Student>();
            obj.Add(new Student() {id=123,name="shibashish",section="A" });
            obj.Add(new Student() { id = 124, name = "shibashish", section = "A" });
            obj.Add(new Student() { id = 125, name = "shibashish1", section = "b" });
            obj.Add(new Student() { id = 126, name = "shibashish2", section = "c" });
            obj.Add(new Student() { id = 127, name = "shibashish3", section = "d" });
        

            return View(obj);
        }
//UserDetails is the method we are going to discuss in this article
        public ActionResult UserDetails(int id)
        {
            StudentContext Studrecords = new StudentContext();
            var obj = from x in Studrecords.userrecords where x.USER_ID == id select x;

            return View(obj);
        }

    }
}

Now right click on UserDetails method and click on Add View.It will create a view as UserDetails.cshtml
Here is the code
@*I have cast it as ienurable looking to  the controller’s return type*@
@model IEnumerable< MySchoolDemoMvcApp.Models.Userdata>
@using MySchoolDemoMvcApp.Models;
@{
    ViewBag.Title = "UserDetails";
}
@*I have designed the form like below to see the data*@

<h2>UserDetails</h2>
<div style="background-color:Gray;color:Red"><h2>Student Deatils</h2>

<table>
@foreach (Userdata item in @Model)
{
  <tr><td>
User Id:
</td><td>@item.USER_ID</td></tr>
<tr><td>
User Name:
</td><td>@item.USERNAME</td></tr>
<tr><td>
Full Name:
</td><td>@item.FULLNAME</td></tr>
 
}


</table>

</div>

After running you will get data like this

Thanks 

Shibashish Mohanty

No comments:

Post a Comment

Please don't spam, spam comments is not allowed here.

.

ShibashishMnty
shibashish mohanty