Showing posts with label EntityFramework. Show all posts
Where I can find SQL Generated by Entity framework?
Few days back I was optimizing the performance with Entity framework and Linq queries and I was using LinqPad and looking SQL generated by the Linq or entity framework queries. After some point of time I got the same question in mind that how I can find the SQL Statement generated by Entity framework?
After some struggling I have managed to found the way of finding SQL Statement so I thought it would be a great idea to write a post about same and share my knowledge about that. So in this post I will explain how to find SQL statements generated Entity framework queries.
To demonstrate the idea Let’s a very simple console application with C# and then create a table called ‘Customer’ with CustomerId and CustomerName field in sql server.
Execute TSQL statement with ExecuteStoreQuery in entity framework 4.0
You can find more information about ExcuteStoreQuery from following link.
http://msdn.microsoft.com/en-us/library/dd487208.aspx
Entity framework and Stored procedure output parameter
So let’s start coding for that.For demo, I have create a table called ‘Customer’ which contains just two columns CustomerId and CustomerName. Following is the script for that.
/****** Object: Table [dbo].[Customer] Script Date: 09/09/2011 00:18:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Customer](
[CustomerId] [int] NOT NULL,
[CustomerName] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED
(
[CustomerId] 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
Now as our table are ready. Let’s create a stored procedure which will return the number of records as output parameter. Following is script for that.
/****** Object: StoredProcedure [dbo].[esp_GetCustomerCount] Script Date: 09/09/2011 00:20:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[esp_GetCustomerCount]
@CustomerCount INT OUTPUT
AS
select @CustomerCount=COUNT(customerId) from Customer
GO
Now our database part is ready so its time to create a entity model. So first I have created a console application and I added a new entity model via project-> right click-> Add new item and selected ADO.NET Entity Model like following.
Once I clicked add a wizard will start asking for choosing model contents like following.
Here I have selected Generate from database and clicked next it will ask for connection string. I have selected connection string and click next it will ask to select object of database. Here I have selected tables and stored procedure which we have created earlier like following.
Now once we have done our model creation its time to create a function import for store procedure. So do that we need to first open Experiment.edmx in visual studio like below.
Once you click Model browser it will reopen model browser in right side of your edmx like following.
Now in your store you need to expand store part and select stored procedure and click Add function import like following to create function for stored procedure.
Once you click Add function import a dialog box will open to select stored procedure and return type like following.
Here I have changed name of function called ‘GetCustomerCount’ now once you click OK it will create a function called ‘GetCustomerCount’ in entity framework model. Now its time to use that in code. Following is the code from where can find the output parameter value.
using System;
namespace ExperimentConsole
{
class Program
{
static void Main(string[] args)
{
using (ExperimentEntities myContext = new ExperimentEntities())
{
System.Data.Objects.ObjectParameter output = new System.Data.Objects.ObjectParameter("CustomerCount", typeof(int));
myContext.GetCustomerCount(output);
Console.WriteLine(output.Value);
}
}
}
}
Here in above code you can see that I have created a object parameter and passed that to function as output parameter is there. Once this function will complete execution it will return value and you can get value with .value property. I have printed that in console application. Following is the output as expected as I have added four records in database.
So that’s it. It’s very easy to use output parameter. Hope you liked it. Stay tuned for more. Till then happy programming.. Namaste!!
Some important attributes in EFCodeFirst
Key Attribute:
When you put this attribute in the class it tell that this property is part of the primary key and If you use code first when its create table based on this entity then it will be a part of primary key of table. Here is the sample example of that.[Key]
public int ArticleId { get; set; }
Here article ID will act as primary key.Foreign Key Attribute:
This attribute is very useful when you deal with interrelated tables You can specify the column in entity which is foreign key for that Like following.[ForeignKey("CategoryId")]
public ICollection<Category> Categories { get; set; }
In above example CategoryId is a foreign key of category table to article table.ScaffoldColumn Attribute:
When you Scaffold your application with ASP.NET MVC scaffold feature or dynamic data with asp.net webforms this attribute will tell that this column need to have field for that. You can write that column like following.[ScaffoldColumn(false)]
public int ArticleId { get; set; }
Here it will tell article id will not have UI in scaffoling.StringLength Attribute:
This attribute is used to specify the maximum length of a string. This attribute is very usefull in validation and other stuff. This attribute only applied to the Stringlength property like following.[StringLength(512)]
public string Title { get; set; }
Here in the above code it tell that title could not have more then 512 character string.There lots of other attributes also. I will blog about it in future posts. Hope you liked this. Stay tuned for more..Happy Programming.
CRUD Operation with ASP.NET MVC and EFCodeFirst Part-2
As you can see in the above template I have selected Customer Model Class for strongly typed view and Selected Scaffold template as Create once you click Add your view will be ready. Now its time to write for code in customer controller to Add Customer. So I have modified Create Method of customer controller which we have created like following.
[HttpPost]
public ActionResult Create(Models.Customer customer)
{
try
{
using (var databaseContext = new Models.MyDataContext())
{
databaseContext.Customer.Add(customer);
databaseContext.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
That's it. We have done with Create Customer now. In the above databasecontext add method will add customer and SaveChanges method will save changed to database.
Now once we are done with Add its time to create edit and update functionality. Let’s first Add a view via Selecting view with Edit Method in clicking on Add view. Once you click a dialogbox for add View will open for that like following.
As you can see you I have selected scaffold template as Edit and I have Created Strongly typed view with Customer class. Once you click add it will create a new view for Edit. Now our Edit View is ready so let’s write code for Edit/Update in database. So first we have to modify Edit(int Id) method like following which will return specific customer with View. Following is a code for that.
public ActionResult Edit(int id)
{
using (var databaseContext = new Models.MyDataContext())
{
return View(databaseContext.Customer.Find(id));
}
}
Now let write code to update the changes to database. So for that I have modified another ActionResult Edit of customer controller like following.
[HttpPost]
public ActionResult Edit(int id, Models.Customer customer)
{
try
{
using (var databaseContext = new Models.MyDataContext())
{
databaseContext.Entry(customer).State= System.Data.EntityState.Modified;
databaseContext.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
That's it we are done with the edit stuff.In above code the state modified will tell databasecontext that customer details is modified and savechanges will save changed to database. Now its time to create view for delete functionality. So I have clicked on Add View and Created a view for delete like following.
Here I have create Strongly typed view with Delete Scaffold Template. Now let’s modified both Delete Action Result in Customer Controller class. First Action result will return customer which we are going to delete and another delete action result with id will delete the customer from database and then it will return to main customer page. I have modified the code for both as following.
// GET: /Customer/Delete/5
public ActionResult Delete(int id)
{
using (var databaseContext = new Models.MyDataContext())
{
return View(databaseContext.Customer.Find(id));
}
}
//
// POST: /Customer/Delete/5
[HttpPost]
public ActionResult Delete(int id,Models.Customer customer)
{
try
{
using (var databaseContext = new Models.MyDataContext())
{
databaseContext.Entry(databaseContext.Customer.Find(id)).State = System.Data.EntityState.Deleted;
databaseContext.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Here I have done something different then editing stuff to demonstrate the feature of Entity framework. You can also use Id for finding the current customer and then change its state to delete and SaveChanges will save that to in database. So now we are done with delete also. It’s now time to create details part. So same as above I have create a view with scaffold template details with customer model like following.
Once we are done with creating view . It’s time to change the code for Details Action Result like following to return current customer detail.
public ActionResult Details(int id)
{
using (var databaseContext = new Models.MyDataContext())
{
return View(databaseContext.Customer.Find(id));
}
}
So that's it. We are done with all the stuff. So with Entity Framework code first. You can create basic CRUD application within 30 minutes without writing so much code. Hope you liked it. Stay tuned for more.. Till that Happy programming.
Getting Started with NuGet Packages step by step overview.
We can all see lots of buzz about NuGet in asp.net world. So I decided to explore it. let’s explore it in some details. Following is a explanation of NuGet Extension on the code plex here.
"NuGet is a Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects that use the .NET Framework. When you add a library or tool, NuGet copies files to your solution and automatically makes whatever changes are needed in your project, such as adding references and changing your app.config or web.config file. When you remove a library, NuGet removes files and reverses whatever changes it made in your project so that no clutter is left."
Installing NuGet
Let’s see how we can install it. For that first you have to go thorough the Tools->Extension Manager and then search for nuget and it will appear in the list like below.
After that click on download and it will download and install it from the web. Make sure your computer has access to internet. Once you download your nugest extension it will ask you to restart visual studio. So once your are restarted you are ready with nuget packages.
How to install packages with NuGet
Here, I am going to install Entity Framework code first CTP 5 package with NuGet. To install that package first you have to go right click your project and then click add Library Reference Package like following.
After that a reference dialog will appear their you have click online and search entity as we need to install entity framework ctp. After searching the right package click on install it will start installing your package. Following is screen host of add library package reference dialog.
After clicking install EFlicence dialog will appear like this.
Click on I Accept and install will install package.After installing package a green icon will appear on top as indication of your successful installation like following.
Now after clicking on close if you see on your project reference An Entity framework is added to your project reference like following.
Also you can see a package.config will be added to your project. like following.
<?xml version="1.0" encoding="utf-8"?>That's it your package is installed and ready to use in your application. There is another way of adding packages with package console is also there. I will explain this on future blog posts. Hope you liked this. Stay tuned for more..
<packages>
<package id="EFCodeFirst" version="0.8" />
</packages>
Entity Framework 4.0- Bind Stored Procedure with Result Entity class
Microsoft Entity Framework version 4.0 is a brand new ORM(Object Relational Mapper) from Microsoft. It’s provides now some new features which are not there in the earlier version of Entity framework. Let’s walk through a simple example of a new features which will create a new Entity class based on stored procedure result. We will use same table for this example for which they have used earlier for Linq Binding with Custom Entity.
Below is the table which have simple fields like first name,last name etc.
Let’s insert some data like following.
Below is the stored procedure which I am going to use for this example which will simply fetch data from the table.
CREATE PROCEDURE dbo.GetAllUsers
AS
SET NOCOUNT ON
SELECT
UserId,
UserName,
FirstName,
LastName,
FirstName + ' ' + LastName AS [FullName]
FROM dbo.Users
Once you click add a dialog box will appear which will ask for Data Model Contents there are two options Generate From Database and another one is Empty Model. Generate from database will create a Entity model from the ready made database while Empty model enable us to create a model first and then it will allow us to create a database from our model. We are going to use Generate From database for this example. Select Generate From Database like following and click Next.
After click on the next it will ask for database connection string like following where you need to apply connection string for that. I am already having connection string in my web.config so i just selected like below otherwise you need to create one via clicking on new connection. Also you need to specify the connection string name in web.config so it will put a connection string in connection string section with that name.
Once you click next it will fetch the all database objects information like Tables,Views and Stored Procedure like following. Here our purpose is to work with stored procedure so I just selected the stored procedure and selected the GetAllUsers Stored Procedure.
After that it will create a Entity Model class in solution explorer.Now we want to bind the stored procedure with result class so first we need to create function which will call ‘GetAllUser’ stored procedure. To create function we just need to select Our Entity Model class and then go to Model Browser and select the Stored Procedure and right click->Add Function Import like following image.
It will start a new wizard and will go to next step like following image which will have four options 1. None 2. Scalars 3. Complex 4. Entities and there will be a button Get Column information once you click it. It will gather all the column information of stored procedure result set and then click ‘Create New Complex Type’ It will create a new complex type from the gathered column information.
You can also rename that class so I have renamed the class as ‘User Info’ like following.
Now click ok and now it will create function which call the stored procedure and will return Object Result set of Type ‘UserInfo’ which we have just created. Now let’s bind that to a simple grid view to see how its works. So Let’s take a simple grid view like below.
<asp:GridView ID="grdUserList" runat="server">
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
using (BlogEntities myEntity = new BlogEntities())
{
grdUserList.DataSource = myEntity.GetAllUsers();
grdUserList.DataBind();
}
}
}
That’s it very easy and simple to bind complex type with stored procedure using ADO.NET Entity Framework 4.0. Hope this will help you.. Happy Programming!!!

