Geeks With Blogs

News

Microsoft MVP


Moderator at CodeASP.NET


Quiz Master




free counters
Free counters
Added on January 19,2012


Follow Me @vmsdurano

A bit About Me



Disclaimer
The opinions expressed herein are my own personal opinions and does not represent the opinions of my employers. Nor does it represent the opinion of my dog, because I don’t have one.


Vinz' Blog (ProudMonkey) "Code, Beer and Music ~ my way of being a programmer"

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:

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.


You can refer the link below for more details about Entity Framework:
http://msdn.microsoft.com/en-us/library/aa697427%28v=vs.80%29.aspx

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!

 

Technorati Tags: ,,
Posted on Monday, April 4, 2011 11:59 AM ASP.NET , C# | Back to top


Comments on this post: Entity Framework - Inserting Data to Database

# re: Entity Framework - Inserting Data to Database
Requesting Gravatar...
This is a great article.....simple and concise and tells u all....
Left by Rohit on Sep 22, 2011 1:06 AM

# re: Entity Framework - Inserting Data to Database
Requesting Gravatar...
Really very nice article.
It helps me a lot...
Left by Avinash on Dec 19, 2011 6:54 PM

# re: Entity Framework - Inserting Data to Database
Requesting Gravatar...
thanks a lot........:)
Left by Puja Roy on Dec 29, 2011 6:14 PM

# re: Entity Framework - Inserting Data to Database
Requesting Gravatar...
sir i have some problem

sir i repeat the same procedure just you are doing in insert database but on button click coding i dont get text boxID in ItemUserInfo

please give me solution

please send the link of update ,fetch and delete data bu entity framework
Left by hitesh on Jan 06, 2012 9:56 PM

# re: Entity Framework - Inserting Data to Database
Requesting Gravatar...
Thanks a lot, sir. I started my learning in entity framework through this website.
could you please advice update and delete operations also !
Left by Sriram on Jan 10, 2012 4:59 PM

# re: Entity Framework - Inserting Data to Database
Requesting Gravatar...
@sriram,

http://geekswithblogs.net/dotNETvinz/archive/2011/04/04/entity-framework---editing-updating-and-deleting-data-in-the.aspx
Left by Vinz on Jan 10, 2012 5:39 PM

# re: Entity Framework - Inserting Data to Database
Requesting Gravatar...
Thanks..very nice article
Left by shefin on Feb 13, 2012 10:40 PM

# re: Entity Framework - Inserting Data to Database
Requesting Gravatar...
Its very nice Tutorial for Beginners....
Left by Sony Patil on Mar 15, 2012 5:52 PM

# re: Entity Framework - Inserting Data to Database
Requesting Gravatar...
Very nyc ..
Left by Sibi on Apr 05, 2012 9:40 PM

# re: Entity Framework - Inserting Data to Database
Requesting Gravatar...
Thanks it really helped me very much..............)
Left by Manju on May 25, 2012 2:18 PM

# re: Entity Framework - Inserting Data to Database
Requesting Gravatar...
thanks
I tested it but it didn't work
i don't know if i missed something
could you explaine step4 again
i didn't understand the code
and for what Add, user and dre is used for
Left by Ace on Jul 17, 2012 6:33 PM

# re: Entity Framework - Updating Data to Database
Requesting Gravatar...
HI can you please help me
Left by Naveed on Sep 18, 2012 9:05 PM

# re: Entity Framework - Inserting Data to Database
Requesting Gravatar...
Thank You!! this was very helpful
Left by Kobie Williams on Feb 15, 2013 11:25 AM

comments powered by Disqus

Copyright © Vincent Maverick Durano | Powered by: GeeksWithBlogs.net | Join free