Showing posts with label Entity Framework. Show all posts
Showing posts with label Entity Framework. Show all posts

Tuesday, February 23, 2010

Call Stored Procedure from Entity Framework


Microsoft have introduced entity framework to connect to the database. When you work with the database, you have to call your stored procedure. This blog explain you how to execute your stored procedure from Entity Framework.

Assume that your stored procedure insert/update/delete record into database. It returns nothing just do as per the parameter value.

Follow the below steps:
1. Open Entity Framework Model page in Visual Studio IDE
2. Right click on blank area and choose “Add” -> “Function Import” option
3. In Add Function Import dialog, select your stored procedure, give function name and choose return type
4. Click on Ok button to add the function in Entity Framework
5. In your page, Create instance of entities class and call your function with proper parameter value

If your stored procedure is return multiple record then you have to create one custom entity, which have the same schema as your stored procedure return the data. To create the custom entity, right click on Entity Framework Model page and choose “Add” -> “Entity…” It will open “Add Entity” dialog box where you have to give Entity Information.

You can add/edit/delete properties into custom activity. To add, Select “Scalar Properties” section under custom activity, right click and choose “Add” -> “Scalar Property”.

Just create custom entity. After creating custom entity, Add Function Import to your entity framework model.

Follow the below steps:
1. Open Entity Framework Model page in Visual Studio IDE
2. Right click on blank area and choose “Add” -> “Function Import” option
3. In Add Function Import dialog, select your stored procedure, give function name and choose return type as Entities and select your custom entity from dropdown list.
4. Click on Ok button to add the function in Entity Framework
5. In your page, Create instance of entities class and call your function with proper parameter value


TestDBEntities1 testdb = new TestDBEntities1();
var p = from d in testdb.GetOrderInfo() select d;

Friday, February 19, 2010

Entity Framework Stored Procedure mapping


Introduction



Now days, Microsoft have changed lots of thing in accessing database from .Net application. Microsoft has introduced Entity Framework to access database from the application. Entity framework is just a small wizard which helps to create classes to access the database. To know basic of Entity Framework please click on here.

In Part 1, I explained you how to create entity framework class in your project and how to insert, update or delete the record. Now in part 2, I explain you how to map your stored procedure with insert, update and delete functionality.

If you will not map your stored procedure then Entity Framework will create concrete SQL statement for insert, update and delete. If you will map your stored procedure then Entity Framework will execute your stored procedure with parameter value.

Let take an example of contact table which I explained schema in part 1.

After creating entity framework file (.edmx), Select “Contact” entity and open “Mapping Details” window. In Mapping Details window, click on “Map Entity to Function” button on left side. Refer below screen shot:




In Insert/Update/Delete function, Select your stored procedure and map your parameter value. Refer image below:



Now you have to just add/update/remove data using Entity Framework and It will execute your mapped stored procedure.

Following code is used to add new record into Contact table. When user will execute the code below, Entity Framework will execute “SPE_ContactInsert” stored procedure to insert contact information.

TestEntityEntities testEntityEntities = new TestEntityEntities();
Contact contact = new Contact();
contact.FirstName = "test1";
contact.LastName = "test2";
contact.Title = "Mr.";
testEntityEntities.AddToContact(contact);
testEntityEntities.SaveChanges();

As the same way you can update or delete the record. For more information please refer Entity Framework part 1 here.

Friday, February 5, 2010

Basic of Entity Framework


Introduction

Microsoft has evolved new technology “Entity Framework” to work with Database. Before this, Microsoft has introduced LINQ to work with the objects which derived from the IEnumerable.

Entity framework is easy to use for developer to generate entity classes for tables/views. Entity framework also generates methods to execute stored procedure which you have created into database.

Entity Framework needs Visual Studio 2008 Service Pack2 installed on the machine.

Developer can easily drag and drop the entity object from server explorer to Entity Framework UI. You can easily generate Entity Framework classes from the existing database. Reverse engineering is not possible in Visual Studio 2008. We can expect this functionality from Visual Studio 2010.

Let’s start with Entity Framework

I have used following database structure to understand Entity framework in .Net application.

Table NameContact
Field NameData TypeConstraint
ContactIDIntPK, Auto Increment
FirstNameVarchar(100)Not Null
LastNameVarchar(100)Not Null
TitleVarchar(50)Not Null
AddDateDateTimeNot Null, Default Value = GetDate()
ModifiedDateDateTimeNot Null, Default Value = GetDate()
Table NameAddress
Field NameData TypeConstraint
AddressIDIntPK, Auto Increment
Street1Varchar(50)
Street2Varchar(50)
CityVarchar(50)
StateProvinceVarchar(50)
CountryRegionVarchar(50)
PostalCodeVarchar(50)
AddressTypeVarchar(50)
ModifiedDateDateTime
ContactIDIntFK


Here we took example of Contact and Address table. One contact person has many addresses like permanent address, office address, Farm-house address etc… So we took “ContactID” field as a foreign key in Address table.

Now let’s create Entity Framework project in .Net IDE.

First open Visual Studio 2008 and select File -> New -> Project option. It will open “New Project” dialog box. Select Project Type “Visual C#” -> “Windows”. Select “Windows Form Application” from Template options. Provide project name, project location and solution name as you want.

Note: You can also take console application or another type of project. But for demo purpose I have chosen windows form application.

After successfully loading project, Right click on project in solution explorer and add new item. In New Item Dialog box select “ADO.Net Entity Data Model” and give name ContactDataModel.edmx. Click on Add button. It will start Entity Framework wizard.
  • In entity framework wizard home page you will get two options “Generate from database” and “Entity model”. You can generate Entity Model using existing database or can use blank entity model to generate your classes manually. [Reverse engineering is not possible in Visual Studio 2008]. Select “Generate from Database” option and click next button
  • In next screen, it allows to create new connection or use existing connection which created before. You can create new connection using “New connection” option. After selecting the proper data connection, Connection string text box will display the connection string used to communicate with the database. You can save the connection string in App.config file. To save connection string in App.Config file just give proper name to “Save entity connection settings in App.config As” textbox. Give “TestEntityEntities” name as connection string name. Click on Next button.
  • In Next screen, you have option to choose which object you want to include in entity framework. You can select Tables, Views and Stored Procedures. Select Address and Contact Table. Click on Finish Button.
  • Entity Framework Wizard will create Entity Framework Model file in your project and option UI in Visual studio. You can see Contact and Address entities.


Entity Framework also generates classes in code behind file for Contact and Address entities. It will generate three classes:
  • Address: This class contains private variables and public properties for each field.
  • Contact: This class contains private variables and public properties for each field.
  • TestEntityEntities: This class is derived from ObjectContext class and has property for Address and Contact entities. This class has method to add new objects in Contact and Address classes.

Now let’s use it in our windows application:

Create new windows form in our windows form application and drag DataGridView control on windows form. Write following code to display all contact information in data grid view.


TestEntityEntities entities = new TestEntityEntities();
var query = from c in entities.Contact select c;
dataGridView1.DataSource = query;

In above code, we created object of the TestEntityEntities class which is generated by Entity Framework wizard in code-behind file. Just use LINQ syntax to get all the contact information from the TestEntityEntities object and display all the contact information in DataGridView object.

Add new record using Entity Framework:

Let go with the Contact Entity. The below code is useful to add new record in contact entity.


TestEntityEntities testEntityEntities = new TestEntityEntities();
Contact contact = new Contact();
contact.FirstName = "test1";
contact.LastName = "test2";
contact.Title = "Mr.";
testEntityEntities.AddToContact(contact);
testEntityEntities.SaveChanges();

First of all we create object of Entities class which is created by Entity Framework. Then after we create object of Contact and assign value to the required properties. After successfully assign value to contact entity, we will call “AddToContact” method of TestEntityEntities class. This method will store the data in Contact table but still the data is not committed. So commit the added data, we need to call “SaveChanges” method of TestEntityEntities class.

Edit existing record using Entity Framework:

To edit any existing record, we need to fetch that record and update it in memory and call SaveChanges method to save the changes. Below code is used to edit existing record.


TestEntityEntities testEntityEntities = new TestEntityEntities();
Contact contact = testEntityEntities.Contact.First(c => c.FirstName == "test1");
contact.FirstName = "test1_Changed";
testEntityEntities.SaveChanges();


First we create object of TestEntityEntities class. Then after we get contact entity record using TestEntityEntities class method. After getting the record, we just need to update the property values and call SaveChanges function.

Deleting existing record:

To delete the record, we need to load the record and delete it using Entity Framework. Below code is used to delete the record.


TestEntityEntities testEntityEntities = new TestEntityEntities();
Contact contact = testEntityEntities.Contact.First(c => c.FirstName == "test1");
testEntityEntities.DeleteObject(contact);
testEntityEntities.SaveChanges();

We just load the record and then call DeleteObject method. This method will not commit your changes to database. To commit the changes, we need to call SaveChanges method.

For more information on how to map stored procedure with Entity, click here.

DotNet Code Guru