/Home /Archive /Syndicate /Blog /Support /About /Contact  
All Visual Basic Feeds in one place!





This is the continuation of the deeper look into the MSDN EF Quickstart.  Part 1 is here.

 

5.   Querying Entities and Associations
a.   To query the departments in the School database

Step 2:   ' Create an ObjectContext instance based on SchoolEntity.
Private schoolContext As SchoolEntities

Although the previous section tells you that generating the EDM:  “Creates a source code file that contains the classes that were generated based on the EDM. You can view the source code file by expanding the .edmx file in the Solution Explorer.” it might not be totally clear that the SchoolEntities class is one of the things that is generated automatically.   As the instructions explain, you can view this class by using Show All Files in the Solution Explorer:

 

Quickstart012

 

  Using the variable named in the code snippet above, you will be able to create an instance of this class which will give you access to the entities and their properties (which you saw in the designer pane of the Model Browser) …..

Step 4.   …. which is exactly what line 3 in the code for the next step does.

 

    1     Private Sub CourseViewer_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    2         ' Initialize the ObjectContext.

    3         schoolContext = New SchoolEntities()

    4 

    5         ' Define a query that returns all Department objects and related

    6         ' Course objects, ordered by name.

    7         Dim departmentQuery As ObjectQuery(Of Department) = _

    8             schoolContext.Department.Include("Course").OrderBy("it.Name")

    9 

   10         Try

   11             ' Bind the ComboBox control to the query, which is

   12             ' executed during data binding.

   13             Me.departmentList.DisplayMember = "Name"

   14             Me.departmentList.DataSource = departmentQuery

   15         Catch ex As Exception

   16             MessageBox.Show(ex.Message)

   17         End Try

   18     End Sub

 

Looking at the above code, you may also wonder about the syntax of the query in lines 7 and 8.   There are several ways of querying the model and the example shown in this Quickstart is a fairly advanced approach.   I plan to write a blog later that demonstrates some of the other ways and you may find one there that suits you better.

So, starting with line 7:   Dim departmentQuery As ObjectQuery(Of Department) = _

The departmentQuery variable is declared to be of type ObjectQuery.   ObjectQuery is a class in the System.Data.Objects namespace, which is why you were instructed to include that Imports statement earlier.   The Entity Framework will create and run a query, (using ObjectQuery), to return objects.   The objects will usually be objects that represent entities in the model.  As you will have seen from the EDM diagram and the database table information, the entities in this case each represent a table from the underlying database.  This particular example targets the Department entity which under the covers maps back to the Department table in the School database.   (If you are wondering about that mapping, it is carried out via an XML file that you haven’t seen in this Quickstart.)

Line 8:   schoolContext.Department.Include("Course").OrderBy("it.Name")

This line demonstrates one way of creating a query and this particular version is known as a Method Query or Method-Based Syntax, hence the periods between each subsection of the query.     It uses Entity SQL for the body of the query.   As I mentioned above, there are alternatives to this.

Department is a property of the SchoolEntities class, so
                  schoolContext.Department
accesses that property in the same way that you would access a property in any class you create.

Next:
                  Include(“Course”)
makes use of the Entity Framework’s ability to use Navigation Properties as the means of creating links between related data.

You can see in the screenshot below, taken from the Model Designer view, that there is an Entity named Department which has a Navigation Property named Course.

Quickstart013

By using the instruction to Include Course, the query is required to fetch not only the Department data but also the Course data for each Department that it finds.

Finally:
     OrderBy("it.Name")

ensures that the returned objects are sorted alphabetically.   The ‘it’ in “it.name” is the default required name for a variable used in a query in this way.  If you change it or leave it out and just write “name”, for example, your application won’t crash but the query will be incomplete and the data will not be fetched or displayable.

The code in the Try Catch block should be relatively familiar to you.  

           Me.departmentList.DisplayMember = "Name"
ensures that the ComboBox uses the Name property of Department for its List Items.

         Me.departmentList.DataSource = departmentQuery
simply sets the data source of the ComboBox to that collection of Department objects returned by the ObjectQuery.

 

To display courses for the selected department
The next block of code displays the related Course data for the currently selected Department:

    1     Private Sub departmentList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles departmentList.SelectedIndexChanged

    2         Try

    3             ' Get the object for the selected department.

    4             Dim department As Department = _

    5                 CType(Me.departmentList.SelectedItem, Department)

    6 

    7             ' Bind the grid view to the collection of Course objects

    8             ' that are related to the selected Department object.

    9             courseGridView.DataSource = department.Course

   10 

   11             ' Hide the columns that are bound to the navigation properties on Course.

   12             courseGridView.Columns("Department").Visible = False

   13             courseGridView.Columns("CourseGrade").Visible = False

   14             courseGridView.Columns("OnlineCourse").Visible = False

   15             courseGridView.Columns("OnsiteCourse").Visible = False

   16             courseGridView.Columns("Person").Visible = False

   17 

   18             courseGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells)

   19         Catch ex As Exception

   20             MessageBox.Show(ex.Message)

   21         End Try

   22     End Sub


The Course data, you will recall, is accessed as a Navigation Property of Department.   This is standard Master-Detail data, but the way it is collected (using Include) is probably different from what you have done in the past.   Displaying it using the Entity Framework is simply a matter of identifying which Course is currently selected in the ComboBox and casting that Selected Item to a Department object instance (Lines 4&5); the Course property of that Department object is then used as the Data Source of the DataGridView (Line 9).

The remaining lines of this code block all deal with the formatting of the display of the DataGridView.   The five visibility settings you see there are used to hide the existence of the five Navigation properties of the Course class.   There are other ways of cherry picking the properties to be included in a display and you won’t always need to use the approach shown here.   It does however give you a quick and uncomplicated way to the desired results.

 

6.   Inserting and Updating Data

  

 Private Sub saveChanges_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles saveChanges.Click

        Try

            ' Save object changes to the database, display a message,

            ' and refresh the form.

            schoolContext.SaveChanges()

            MessageBox.Show("Changes saved to the database.")

            Me.Refresh()

        Catch ex As Exception

            MessageBox.Show(ex.Message)

        End Try

    End Sub

 

Given that the purpose of this Quickstart is to fire up your enthusiasm for a new technology and encourage you to pursue it further, this particular section will almost certainly fails that test for most people.   On the positive side, it does introduce a very useful method of the ObjectContext class – SaveChanges.   When used in a fully functional way, this neat little method will carry out any delete or insert tasks, or edit updates required on any properties of any entity in scope.  

The ObjectContext maintains a continuing record of the state of any changes to entities.  When SaveChanges is called, the ObjectContext checks each ObjectStateEntry for details of changes and, where there are any, these are then persisted back to the underlying database.    

For a number of reasons, the sample in the Quickstart will only successfully handle :

Edits to the Title and Credits property of a course.
Inserts of new entities (but doesn’t allow the setting of a Course number)

So, you won’t be able to change an existing Course number or insert a new one and there’s no mechanism within the sample to delete an entity.

You can see some changes I’ve made to the original database in the screenshot below:

Quickstart014

In spite of the limited change options that are included, the Quickstart does offer a quick view of the potential of the Entity Framework which hopefully will encourage you to look deeper into this topic.

I plan to come back to this Quickstart in another blog item and suggest some changes to various parts, offer alternative syntax and different approaches in some cases and demonstrate the various adding, editing and deleting tasks in action.

© 2005 Serge Baranovsky. All rights reserved.
All feed content is property of original publisher. Designated trademarks and brands are the property of their respective owners.

This site is maintained by SubMain(), a division of vbCity.com, LLC