ASP.NET 4.0 and the Entity Framework 4 - Part 2: Perform CRUD Operations Using the Entity Framework 4
page 4 of 8
by Vince Varallo
Feedback
Average Rating: 
Views (Total / Last 10 Days): 85565/ 135

Step 3: Selecting Records to Load a Drop Down List

The first task we'll do is to load the drop down list in the page load event with the list of records in the UserAccounts table.  We'll also add an extra entry in the list to allow the user to select the option of creating a new user.

1.    Double click on the web form in Design view to create the Page_Load event in the code behind.

2.    Add the following code to the Page_Load event.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        LoadUserDropDownList();
    }
}

3.    The LoadUserDropDownList is a custom method that you must create.

private void LoadUserDropDownList()
{
  using (OrderDBContainer db = new OrderDBContainer())
  {              
    ddlUsers.DataSource = from u in db.UserAccounts
                       orderby u.LastName
                 select new { Name = u.LastName + ", " + u.FirstName, Id = u.Id };
 
    ddlUsers.DataTextField = "Name";
    ddlUsers.DataValueField = "Id";
    ddlUsers.DataBind();
 
    ddlUsers.Items.Insert(0, new ListItem("Create New User"""));
  }
}

This method creates and an instance of the OrderDBContainer class which was created when you created the OrderDB.edmx file.  This object acts similar to a connection object in ADO.NET.  You use the OrderDBContainer to "connect" to the database and manipulate the entities defined within it.  The drop down list's DataSource source property is set to the results of a LINQ query.  The Entity Framework will translate this syntax into a SQL statement.  The syntax for writing LINQ queries takes some time to get used to because it's backwards from SQL.  The FROM clause comes first and the SELECT clause comes last.   In this example, I'm selecting all the records from the UserAccounts table and ordering them by their last name.  In the select clause I'm creating a dynamically generated object with two properties called Name and Id.  The Name is what will be displayed to the user in the drop down list.  I'm concatenating the Last and First name and separating them by a comma. 

The DataTextField is then set to "Name" which is the property in the dynamically created object.  The DataValueField is then set to "Id".  The next line binds the data to the drop down list.  The call to the database doesn't actually get made until this line is executed.  The last line adds a new item to the list in the first position.  The text of the item is "Create New User" and this will be used to determine if the user is adding or updating an existing user.

Set this page as the startup page and run the project.  There are no records in the table yet so all you'll see is the "Create New User" entry in the drop down list.  If you were to turn on SQL Server Profiler you would see the SQL statement that the Entity Framework executed against the database to retrieve the records.

SELECT 
[Project1].[Id] AS [Id], 
[Project1].[C1] AS [C1]
FROM ( SELECT 
      [Extent1].[Id] AS [Id], 
      [Extent1].[LastName] AS [LastName], 
      [Extent1].[LastName] + N', ' + [Extent1].[FirstName] AS [C1]
      FROM [dbo].[UserAccounts] AS [Extent1]
)  AS [Project1]
ORDER BY [Project1].[LastName] ASC

View Entire Article

User Comments

Title: oussama   
Name: skksll
Date: 2012-11-26 9:58:51 AM
Comment:
great
Title: Very Good Article   
Name: cafeasp
Date: 2012-06-25 11:07:38 AM
Comment:
I just try the 'Update' code and it works perfect!

Thanks for sharing this info.
Title: Help there are erros in executing the sql file   
Name: Silver
Date: 2012-01-27 12:42:52 AM
Comment:
Msg 911, Level 16, State 1, Line 1
Database 'OrderSystem' does not exist. Make sure that the name is entered correctly.
Msg 262, Level 14, State 1, Line 17
CREATE TABLE permission denied in database 'master'.
Msg 262, Level 14, State 1, Line 3
CREATE TABLE permission denied in database 'master'.
Msg 4902, Level 16, State 1, Line 7
Cannot find the object "dbo.UserAccounts" because it does not exist or you do not have permissions.
Msg 4902, Level 16, State 1, Line 3
Cannot find the object "dbo.Addresses" because it does not exist or you do not have permissions.
Msg 4902, Level 16, State 1, Line 7
Cannot find the object "dbo.Addresses" because it does not exist or you do not have permissions.
Title: images   
Name: k k h
Date: 2011-12-09 2:25:39 PM
Comment:
Images are broken.
Title: CRUD operation   
Name: Suvashis
Date: 2011-04-07 6:45:55 AM
Comment:
Lots of thanks for the EF 4.0 CRUD Operation understanding
Title: You are the man   
Name: LukTar
Date: 2011-02-07 5:19:08 PM
Comment:
Big respect for YOU. Great article which helped me a lot.
Title: Great Work   
Name: Mayank
Date: 2010-10-29 4:26:15 AM
Comment:
It very helpful article to understand the initial CRUD operations using Entity Framework 4

Thanks a lot
Title: trusted   
Name: david zing
Date: 2010-07-05 7:35:59 PM
Comment:
ent:
I can´t use the lines the code below to update the entity:

db.UserAccounts.Attach(userAccount);
db.ObjectStateManager.ChangeObjectState(userAccount, System.Data.EntityState.Modified);

on the first line I get the message: Attach is not a member of System.Data.Objects.ObjectQuery(Of...)

What´s wrong ?
Title: Mr   
Name: David Zing
Date: 2010-06-09 6:52:52 AM
Comment:
I can´t use the lines the code below to update the entity:

db.UserAccounts.Attach(userAccount);
db.ObjectStateManager.ChangeObjectState(userAccount, System.Data.EntityState.Modified);

on the first line I get the message: Attach is not a member of System.Data.Objects.ObjectQuery(Of...)

What´s wrong ?
Title: N-Tier?   
Name: V. Jenks
Date: 2010-05-10 10:43:30 AM
Comment:
I'd love to see an article this straightforward and approachable in an n-tier tutorial? The EF seems very simple until you try and separate concerns. What if I'd like to store all of my business logic and data access in a separate class library project?
Title: Very good intro   
Name: Marshall
Date: 2010-05-05 2:23:05 PM
Comment:
Great intro to EF and made very simple to understand.
Title: Thanks   
Name: Soyka
Date: 2010-05-05 1:30:11 AM
Comment:
I'm coding just for fun and sometimes I don't know where to start with a new thing. Your articles put me on the right track...Thanks
Title: Far Too Good   
Name: Sreedevi
Date: 2010-03-31 7:14:48 AM
Comment:
This is a very nice article. Its seems like a cake walk creating applications using VS2010. Hope we get to work on VS 2010 very soon.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2019 ASPAlliance.com  |  Page Processed at 2019-03-25 6:41:15 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search