I have already written several post about Linq its a great ORM that we can use in various way. The purpose of this post to demonstrate How we can bind custom entity to stored procedure result with use of Linq-To-SQL. Let’s go through it and you will realize that how easy it will be to bind a Custom Entity to Stored Procedure result.
Let’s first create a simple table to which will hold the user data. It will contain four field like UserId,UserName,FirstName and LastName like following.
Now let’s insert some data into the table like following.
Now let’s create a stored procedure which will return the table data and a new field called Full Name like following. Here full name is a combination of first name and last name
CREATE PROCEDURE dbo.GetAllUsers AS SET NOCOUNT ON SELECT UserId, UserName, FirstName, LastName, FirstName + ' ' + LastName AS [FullName] FROM dbo.Users
Now let’s add a New Entity Class called UserInfo into Linq-To-SQL DataContext via Right Click Add New Class Just like following.After adding class I have added same property as its having in user table and Hence our UserInfo Class will look like following.
Now everything is ready Custom Entity Class called UserInfo and we have Our Function ready which will return Stored Procedure output. Here Linq-To-SQL Provides a property called ReturnType If you select function which we have created via dragging a stored procedure in data context class. We just need to select our UserInfo class there just like following and it will bind the stored procedure with that particular UserInfo class. here only condition should be satisfied that Our Custom Entity class should contain all the field with compatible .NET Data types which will return the data. Below is the property which we are talking about.
Now let’s add grid view to default.aspx page like following and Let’s bind output of stored procedure to that grid view.
<asp:GridView ID="grdUserList" runat="server"> </asp:GridView>
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { using (MyBlogDataContextDataContext myContext = new MyBlogDataContextDataContext()) { List<UserInfo> MyUserList = myContext.GetAllUsers().ToList<UserInfo>(); grdUserList.DataSource = MyUserList; grdUserList.DataBind(); } } }
That’s it its very easy.. Hope this will help you…
0 comments:
Post a Comment
Your feedback is very important to me. Please provide your feedback via putting comments.