Friday, December 30

Entity Data Model Screen Shot

Few months ago I wrote a series of articles regarding how to Insert, Update, Fetch and Delete data in the form using LINQ to SQL. You can view the series of articles below Which i modified Recently:

In this article I'm going to demonstrate the basics on how to work with MS Entity Framework. Basically in this part I'm going to show you how to add data from the WebForm to the database using the MS Entity Framework.

As an overview, ADO.NET Entity Framework (EF) is an object-relational mapping (ORM) framework for the .NET Framework.EF enables developers to create data access applications by programming against a conceptual application model instead of programming directly against a relational storage schema. The goal is to decrease the amount of code and maintenance required for data-oriented applications. Entity Framework applications provide the following benefits:

    * Applications can work in terms of a more application-centric conceptual model, including types with inheritance, complex members, and relationships.
    * Applications are freed from hard-coded dependencies on a particular data engine or storage schema.
    * Mappings between the conceptual model and the storage-specific schema can change without changing the application code.
    * Developers can work with a consistent application object model that can be mapped to various storage schemas, possibly implemented in different database management systems.
    * Multiple conceptual models can be mapped to a single storage schema.
    * Language-integrated query (LINQ) support provides compile-time syntax validation for queries against a conceptual model.



STEP 1: Setting up the project

For this demo, I'm going to use Visual Studio 2010. Now lets go ahead and fire up Visual Studio and then select File -> New Project -> Visual C# -> Web - ASP.NET Web Application and then name the application the way you want and then click OK to generate the default files.

STEP 2: Adding the EDMX file

Now add a new folder under the root of the application and name it as "Model" and within that folder add another folder and name it as "DB". The application structure would look something like below:



After that right click on the "DB" folder and select Add -> New Item -> Data -> ADO.NET Entity Data Model. See below screenshot for more clearer view:



Noticed that I named the entity as "SampleModel" just for the purpose of this demo. You may want to name it to a more appropriate name based on your requirements but for this example let's just use "SampleModel". Now click Add to continue and on the next step select "Generate from database" and click Next. On the next step you can connect or browse to the database that you want to use in the application and test the connection string by clicking on the "Test Connection" button and if it succeeds then you can continue by clicking OK and then Next.

Note that in this example I created a simple database called "DeveloperReport.mdf" and added it into the application's App_Data folder and use it as our database for this demo. See the screen shot below:



On the next step we can add the table(s), views or stored procedures that we want to use in the application by selecting the checkbox. See below screenshot:


Noticed that I've only selected the "SysUser" table. This is because we are going to use this table for doing insert and we don't need anything else. Now click on Finish button to generate the entity model for you. See the screenshot below:



What happens there is that EF will automatically generates the Business object for you within the Entity Data Model(EDM) that we have just created and let you query against it.The EDM is the main gateway by which you retrieve objects from the database and resubmit changes.

STEP 3: Setting up the form

Since we already have our model in place then let's go ahead a set up our GUI. Let's add a new webform by right clicking on the project and select Add -> New Item -> Web -> Webform using Master Page and then click Add. For the simplicity of this demo I just set up the GUI like below:


<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebAppDemo.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h1>Add New</h1>
    <table>
        <tr>
            <td>First Name</td>
            <td><asp:TextBox ID="tbFirstName" runat="server" /></td>
        </tr>
        <tr>
            <td>Last Name</td>
            <td><asp:TextBox ID="tbLastName" runat="server" /></td>
        </tr>
        <tr>
            <td>Contact Number</td>
            <td><asp:TextBox ID="tbContactNumber" runat="server" /></td>
        </tr>
        <tr>
            <td>Login ID</td>
            <td><asp:TextBox ID="tbLoginID" runat="server" /></td>
        </tr>
        <tr>
            <td>Password</td>
            <td><asp:TextBox ID="tbPassword" runat="server" TextMode="Password" /></td>
        </tr>
    </table>
    <br />
    <asp:Label ID="lblMessage" runat="server" />
    <br />
    <asp:Button ID="btnAdd" runat="server" Text="Add" />
</asp:Content>

STEP 4: Creating the Object Manager class

The next step that we are going to do is create an object manager class that would handle the (CRUD operations) create,update,fetch and delete of a certain table. The purpose of this class is to separate the actual data opertions from our code behind and to have a central class for handling insert,update,fetch and delete operations. But please note that in this example I'm only doing the insert part in which a user can add new data from the GUI to the database. I'll talk about how to do the update,fetch and delete in EF in my next article. So this time we'll just focus on the insertion part first.

Now right click on the "Model" folder and add a new class by selecting Add -> Class and since we are going to manipulate the SysUser table then we will name the class as "UserManager". Here's the code block for the "UserManager.cs" class:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebAppDemo.Model.DB;

namespace WebAppDemo.Model {
    public class UserManager {

        private DeveloperReportEntities dre = new DeveloperReportEntities();

        public void Add(string firstName, string LastName,string contactNumber, string loginID, string password) {
            SysUser user = new SysUser();
            user.FirstName = firstName;
            user.LastName = LastName;
            user.ContactNumber = contactNumber;
            user.SysUserLoginID = loginID;
            user.SysPassword = password;

            dre.AddToSysUsers(user);
            dre.SaveChanges();
        }
    }
}

STEP 5: Adding new data to database

Now switch to the WebForms code behind part and create a method that would call the object manager class to do insertion. Here's the code block below:
using System;
using WebAppDemo.Model;

namespace WebAppDemo {
    public partial class WebForm1 : System.Web.UI.Page {

        private void InsertUserInfo(string firstName, string LastName, string contactNumber, string loginID, string password) {
            UserManager userMgr = new UserManager();
            userMgr.Add(firstName, LastName, contactNumber, loginID, password);
        }

        protected void Page_Load(object sender, EventArgs e) {

        }

        protected void btnAdd_Click(object sender, EventArgs e) {
            //You may validate the data first here
            //But assuming the data that was supplied are correct and valid
            InsertUserInfo(tbFirstName.Text,
                           tbLastName.Text,
                           tbContactNumber.Text,
                           tbLoginID.Text,
                           tbPassword.Text);

            lblMessage.Text = "Data Inserted!";

        }
    }
}

Note that I have never included some basic validations on the form such us data inputs, data formats and loginID and password
validation because I want to keep this demo as simple as possible. In real projects you should ensure that all data inputs are validated before sumbitting it to the database.

Here's the sample screen shot when viewing the page in the browser:



And here's the screenshot of the SysUser table after inserting the data from the WebForm:



That's it! I hope someone find this post useful!


Thanks shibashish mohanty

No comments:

Post a Comment

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

.

ShibashishMnty
shibashish mohanty