<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Beth Massi - Sharing the goodness that is VB : Data</title><link>http://blogs.msdn.com/bethmassi/archive/tags/Data/default.aspx</link><description>Tags: Data</description><dc:language>en-US</dc:language><generator>CommunityServer 2.1 SP1 (Build: 61025.2)</generator><item><title>Building Occasionally Connected Smart Clients with WPF</title><link>http://blogs.msdn.com/bethmassi/archive/2009/11/02/building-occasionally-connected-smart-clients-with-wpf.aspx</link><pubDate>Mon, 02 Nov 2009 22:57:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9916434</guid><dc:creator>Beth Massi</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/bethmassi/comments/9916434.aspx</comments><wfw:commentRss>http://blogs.msdn.com/bethmassi/commentrss.aspx?PostID=9916434</wfw:commentRss><wfw:comment>http://blogs.msdn.com/bethmassi/rsscomments.aspx?PostID=9916434</wfw:comment><description>&lt;p&gt;This month Dev Pro Connections has an article by Milind Lele on using Sync Services in a WPF application:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.devproconnections.com/tabId/180/itemId/4586/Building-Occasionally-Connected-Smart-Clients-with.aspx" target="_blank"&gt;Building Occasionally Connected Smart Clients with WPF&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;With Sync Services and Visual Studio 2008 you can visually design your local data cache and have it automatically synchronize your data with the backend remote database. So instead of figuring out your own caching mechanisms on the client, you can use SQL CE to store the local data and then use the sync framework to merge data with the backend.&lt;/p&gt;  &lt;p&gt;If you’re looking to improve scalability of your client applications then you should consider caching data that is read-only, user-specific, changes rarely, or can tolerate some staleness. ADO.NET Sync Services can really help here. &lt;/p&gt;  &lt;p&gt;You can catch more of Milind and team over on the VS Data Team Blog: &lt;a title="http://blogs.msdn.com/vsdata/" href="http://blogs.msdn.com/vsdata/"&gt;http://blogs.msdn.com/vsdata/&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Enjoy!&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9916434" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/bethmassi/archive/tags/VS2008/default.aspx">VS2008</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/SQL+Server/default.aspx">SQL Server</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/DevCenter/default.aspx">DevCenter</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Article/default.aspx">Article</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Data/default.aspx">Data</category></item><item><title>Inserting Master-Detail Data into a SQL-Server Compact Edition Database</title><link>http://blogs.msdn.com/bethmassi/archive/2009/09/15/inserting-master-detail-data-into-a-sql-server-compact-edition-database.aspx</link><pubDate>Wed, 16 Sep 2009 05:11:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9895646</guid><dc:creator>Beth Massi</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/bethmassi/comments/9895646.aspx</comments><wfw:commentRss>http://blogs.msdn.com/bethmassi/commentrss.aspx?PostID=9895646</wfw:commentRss><wfw:comment>http://blogs.msdn.com/bethmassi/rsscomments.aspx?PostID=9895646</wfw:comment><description>&lt;P&gt;Yesterday John posted on the &lt;A href="http://blogs.msdn.com/vsdata/default.aspx" mce_href="http://blogs.msdn.com/vsdata/default.aspx"&gt;Visual Studio Data&lt;/A&gt; blog how to &lt;A href="http://blogs.msdn.com/vsdata/archive/2009/09/14/refresh-the-primary-key-identity-column-during-insert-operation.aspx" mce_href="http://blogs.msdn.com/vsdata/archive/2009/09/14/refresh-the-primary-key-identity-column-during-insert-operation.aspx"&gt;Refresh the Primary Key Identity Column during an Insert Operation&lt;/A&gt; using SQL Server. In that post he shows how the DataSet designer sets up a batch Insert statement to retrieve identity keys automatically. A while back &lt;A href="http://blogs.msdn.com/bethmassi/archive/2009/05/14/using-tableadapters-to-insert-related-data-into-an-ms-access-database.aspx" target=_blank mce_href="http://blogs.msdn.com/bethmassi/archive/2009/05/14/using-tableadapters-to-insert-related-data-into-an-ms-access-database.aspx"&gt;I wrote about how to insert data into an Access database using TableAdapters and identity keys&lt;/A&gt;. Because Access doesn’t support batch statements, the Visual Studio Dataset designer doesn’t generate the code to retrieve the identity on new rows, so you end up having to write a bit of code yourself to do this as I showed in that post. &lt;/P&gt;
&lt;P&gt;Since then I’ve had similar questions about how to do the same thing but using a SQL CE (Compact Edition) database so I thought I’d present the updated code to work with this type of database. Let’s take a look at how to do that, but first some background. (If you don’t care, just skip to the end for the code and &lt;A href="http://code.msdn.microsoft.com/InsertSQLCE/" target=_blank mce_href="http://code.msdn.microsoft.com/InsertSQLCE/"&gt;sample download&lt;/A&gt; ;-))&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;What is SQL-Server Compact Edition (SQL CE)?&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;&lt;A href="http://msdn.microsoft.com/en-us/library/ms172448.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/library/ms172448.aspx"&gt;SQL CE&lt;/A&gt; is a file-based, single-user database that is really handy to use as local storage for your client applications because of its small footprint. And it’s included with Visual Studio 2008. &lt;A href="http://msdn.microsoft.com/en-us/library/ms172417.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/library/ms172417.aspx"&gt;Check out what’s new in SQL CE 3.5 here&lt;/A&gt;. One very typical use of SQL CE is as a local data cache to your SQL Server backend data using sync services in order to create an &lt;A href="http://msdn.microsoft.com/en-us/library/bb384572.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/library/bb384572.aspx"&gt;occasionally connected application&lt;/A&gt;. You can &lt;A href="http://msdn.microsoft.com/en-us/library/cc281959.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/library/cc281959.aspx"&gt;learn about the sync framework here&lt;/A&gt; and &lt;A href="http://msdn.microsoft.com/en-us/library/bb384585.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/library/bb384585.aspx"&gt;how to create a local data cache in Visual Studio 2008 here&lt;/A&gt;. &lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Setting up Parent-Child Tables and Relationships in SQL CE 3.5 Using Visual Studio 2008&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;To add a local database file to your Visual Studio 2008 project just select Add –&amp;gt; New Item, choose the Data category and then select Local Database. This will add a SQL CE database file with an .sdf extension to your project.&lt;/P&gt;
&lt;P&gt;&lt;A href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_2.png" target=_blank mce_href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_2.png"&gt;&lt;IMG style="BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; DISPLAY: inline; BORDER-TOP: 0px; BORDER-RIGHT: 0px" title=image border=0 alt=image src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_thumb.png" width=681 height=410 mce_src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_thumb.png"&gt;&lt;/A&gt;&lt;/P&gt;
&lt;P&gt;This will trigger the Data Sources wizard to start but first we need to create some tables in our database so cancel the wizard. Next open up the Server Explorer (or Database Explorer if you are using VS Express) and you should see your SQL CE database listed under Data Connections. Expand the database node and then right-click on Tables and select &lt;STRONG&gt;New Table&lt;/STRONG&gt;. A dialog will open that allows you to design your table schema. &lt;/P&gt;
&lt;P&gt;For this example I’ll create a parent Categories table and a child Products table with just a few fields to illustrate the concepts here. It’s important when you create a primary key that you choose the &lt;STRONG&gt;int&lt;/STRONG&gt; data type, set Unique to &lt;STRONG&gt;Yes&lt;/STRONG&gt; and then below in the column properties you set Identity to &lt;STRONG&gt;True&lt;/STRONG&gt;. This will create an auto-incrementing, unique primary key. &lt;/P&gt;
&lt;P&gt;&lt;A href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_6.png" target=_blank mce_href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_6.png"&gt;&lt;IMG style="BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; DISPLAY: inline; BORDER-TOP: 0px; BORDER-RIGHT: 0px" title=image border=0 alt=image src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_thumb_2.png" width=681 height=556 mce_src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_thumb_2.png"&gt;&lt;/A&gt; &lt;/P&gt;
&lt;P&gt;Click OK when you’re done and then repeat the same process to add a new Products table. This time though we need to specify a field for the CategoryID foreign key and I’m going to make this a required field by setting Allow Nulls to &lt;STRONG&gt;No&lt;/STRONG&gt;. &lt;/P&gt;
&lt;P&gt;&lt;A href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_8.png" target=_blank mce_href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_8.png"&gt;&lt;IMG style="BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; DISPLAY: inline; BORDER-TOP: 0px; BORDER-RIGHT: 0px" title=image border=0 alt=image src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_thumb_3.png" width=679 height=551 mce_src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_thumb_3.png"&gt;&lt;/A&gt; &lt;/P&gt;
&lt;P&gt;Now we need to add a relationship between these tables so that our little database will maintain referential integrity for us. We’re saying that a Product cannot exist without specifying a Category. We want the database to enforce this so that if we try to delete a Category it will prevent us from doing so if there are any Products. SQL CE 3.5 can maintain this kind of referential integrity for us, just go back to the Server Explorer and right-click on the Products table again but this time select &lt;STRONG&gt;Table Properties&lt;/STRONG&gt;. Select the &lt;STRONG&gt;Add Relations &lt;/STRONG&gt;page.&lt;/P&gt;
&lt;P&gt;&lt;A href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_10.png" target=_blank mce_href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_10.png"&gt;&lt;IMG style="BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; DISPLAY: inline; BORDER-TOP: 0px; BORDER-RIGHT: 0px" title=image border=0 alt=image src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_thumb_4.png" width=713 height=581 mce_src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_thumb_4.png"&gt;&lt;/A&gt; &lt;/P&gt;
&lt;P&gt;Type in the name of the relation you want to create and then select the Foreign Key Table Column, in my case I select CategoryID. Notice that you can also set up cascading or set null/default update and delete rules as well, but for this example we want to leave the rules as NO ACTION. Click Add Columns button then Add Relations button then click OK to save and close. &lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Setting up the Parent-Child DataSet &lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;Now that we have the database set up we can design our DataSet. This is going to be almost exactly the same as &lt;A href="http://blogs.msdn.com/bethmassi/archive/2009/05/14/using-tableadapters-to-insert-related-data-into-an-ms-access-database.aspx" target=_blank mce_href="http://blogs.msdn.com/bethmassi/archive/2009/05/14/using-tableadapters-to-insert-related-data-into-an-ms-access-database.aspx"&gt;how we set up our Access DataSet here&lt;/A&gt; so take a look at that post for the screen-shots, they’ll be the same here. To recap, you need to make sure you set up the relationship on the DataSet properly so that the primary key on the parent will cascade to the foreign key on the child. Right click on the relation in the DataSet designer and select "Both Relation and Foreign Key Constraint" and then set the Update and Delete rules to &lt;STRONG&gt;Cascade&lt;/STRONG&gt;. &lt;/P&gt;
&lt;P&gt;&lt;A href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_12.png" target=_blank mce_href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_12.png"&gt;&lt;IMG style="BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; MARGIN: 0px 20px 0px 0px; DISPLAY: inline; BORDER-TOP: 0px; BORDER-RIGHT: 0px" title=image border=0 alt=image align=left src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_thumb_5.png" width=228 height=341 mce_src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_thumb_5.png"&gt;&lt;/A&gt;The other important thing you need to do is set the Primary Key fields on both DataTables to ReadOnly &lt;STRONG&gt;False&lt;/STRONG&gt;. We need to do this so we can set them in code and have the DataRelation cascade rules work correctly.&lt;/P&gt;
&lt;P&gt;The DataSet designer will set all the rest of the properties and statements up correctly so you don’t have to modify anything else, though I do encourage you to take a look through them. One important thing to notice is the AutoIncrement, AutoIncrementSeed and AutoIncrementStep properties here. These are set to True, –1 and –1 respectively. This means that on the DataSet (client side) the referential integrity on new rows is maintained between the products and categories DataTables using temporary primary keys that are negative integers. &lt;STRONG&gt;These do NOT correspond to the keys in the database for new rows.&lt;/STRONG&gt; It’s not until we send the updates to the database that we get the real identity keys so keep that in mind. (And these properties are the same regardless if you are using SQL CE, Access, or SQL Server identity keys.)&lt;/P&gt;
&lt;P&gt;Okay so now we are ready to design our master-detail form. This should be a familiar process at this point but just in case here’s a recap. Open the Data Sources window (Main Menu –&amp;gt; Data –&amp;gt; Show Data Sources) and you should see the Categories and Products DataTables that are in the DataSet we just created. Design your Master-Detail form like normal. For this example I drag the Categories as details and then select the &lt;EM&gt;related &lt;/EM&gt;Products by expanding the Categories node and dragging the Products table under there. This will set up a relationship on the form as well so that when we select a Category, it will only show those related products. This is also important to get our inserts to work correctly because the temporary identity key (-1, –2, –3, etc) on the CategoryID will automatically cascade to the Product’s CategoryID. &lt;/P&gt;
&lt;P&gt;&lt;A href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_16.png" target=_blank mce_href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_16.png"&gt;&lt;IMG style="BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; DISPLAY: inline; BORDER-TOP: 0px; BORDER-RIGHT: 0px" title=image border=0 alt=image src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_thumb_7.png" width=675 height=380 mce_src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_thumb_7.png"&gt;&lt;/A&gt; &lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Loading and Editing the Parent-Child DataSet&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;Now that the DataSet is set to enforce the foreign key relationships, this means that you &lt;STRONG&gt;must&lt;/STRONG&gt; have a parent for every child so you have to load the data in parent then child order. Remember, you have to &lt;STRONG&gt;make sure that every row in the child DataTable will have a corresponding parent row in the parent DataTable&lt;/STRONG&gt;. This also means that you have to make sure to call EndEdit on any new parent BindingSource before any children can be added. I’m doing this by adding a handler to the grid’s Enter event. So the code-behind for this form is the same as the &lt;A href="http://code.msdn.microsoft.com/AccessDataVS/" target=_blank mce_href="http://code.msdn.microsoft.com/AccessDataVS/"&gt;Access sample I showed before&lt;/A&gt;:&lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;Public Class &lt;/SPAN&gt;Form1

    &lt;SPAN style="COLOR: blue"&gt;Private Sub &lt;/SPAN&gt;CategoriesBindingNavigatorSaveItem_Click() _&lt;BR&gt;                &lt;SPAN style="COLOR: blue"&gt;Handles &lt;/SPAN&gt;CategoriesBindingNavigatorSaveItem.Click
        &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.Validate()
        &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.CategoriesBindingSource.EndEdit()
        &lt;SPAN style="COLOR: green"&gt;'Make sure to call EndEdit on all BindingSources before an update
        &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.ProductsBindingSource.EndEdit()
        &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.TableAdapterManager.UpdateAll(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.MyDatabaseDataSet)
    &lt;SPAN style="COLOR: blue"&gt;End Sub

    Private Sub &lt;/SPAN&gt;Form1_Load() &lt;SPAN style="COLOR: blue"&gt;Handles MyBase&lt;/SPAN&gt;.Load
        &lt;SPAN style="COLOR: green"&gt;'Load parent before child because contraints are enabled on the DataSet
        &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.CategoriesTableAdapter.Fill(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.MyDatabaseDataSet.Categories)
        &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.ProductsTableAdapter.Fill(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.MyDatabaseDataSet.Products)
    &lt;SPAN style="COLOR: blue"&gt;End Sub
   
    Private Sub &lt;/SPAN&gt;ProductsDataGridView_Enter() &lt;SPAN style="COLOR: blue"&gt;Handles &lt;/SPAN&gt;ProductsDataGridView.Enter
        &lt;SPAN style="COLOR: green"&gt;'You must commit the parent row to the DataTable before adding child rows 
        &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.CategoriesBindingSource.EndEdit()
    &lt;SPAN style="COLOR: blue"&gt;End Sub
End Class&lt;/SPAN&gt;&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;&lt;STRONG&gt;Adding Code to Handle Inserts to SQL CE Databases&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;We need a way to set the primary key on the parent right after the row is inserted into the database and before any children are inserted. Now that we have keys cascading we just need to write code to handle the RowUpdated event on the DataAdapter inside the TableAdapter partial class. TableAdapters are generated classes that Visual Studio creates for us from the DataSet designer. These classes are declared as &lt;A href="http://msdn.microsoft.com/en-us/library/yfzd5350.aspx" mce_href="http://msdn.microsoft.com/en-us/library/yfzd5350.aspx"&gt;Partial Classes&lt;/A&gt; so that means we can add code to the same class even if it’s in a separate file. Right-click on the TableAdapter class in the DataSet Designer and select View Code and the partial class file that you can edit will be created for you.&lt;/P&gt;
&lt;P&gt;Now we can write code to automatically query the database for the identity key because SQL CE supports the @@IDENTITY command just like Access. We need to execute this query after each &lt;STRONG&gt;new &lt;/STRONG&gt;row has been inserted into the database, but before any children. If you’re using Visual Studio 2008 then the TableAdapterManager will handle sending parents first then children for insert operations so all we need to do is handle the DataAdapter’s RowUpdated event. Here’s the complete code listing for the DataSet and TableAdapter partial classes which includes code to set default values on the new rows. Notice it’s very similar to the Access code.&amp;nbsp; We’re just working with a different data access client library by importing the System.Data.SqlServerCe instead of System.Data.OleDb.&lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;Imports &lt;/SPAN&gt;System.Data.SqlServerCe

&lt;SPAN style="COLOR: blue"&gt;Public Class &lt;/SPAN&gt;SQLCEIDHelper
    &lt;SPAN style="COLOR: green"&gt;''' &lt;/SPAN&gt;&lt;SPAN style="COLOR: gray"&gt;&amp;lt;summary&amp;gt;
    &lt;/SPAN&gt;&lt;SPAN style="COLOR: green"&gt;''' Retrieves the primary key auto-number identity values from SQL CE
    ''' &lt;/SPAN&gt;&lt;SPAN style="COLOR: gray"&gt;&amp;lt;/summary&amp;gt;
    &lt;/SPAN&gt;&lt;SPAN style="COLOR: green"&gt;''' &lt;/SPAN&gt;&lt;SPAN style="COLOR: gray"&gt;&amp;lt;remarks&amp;gt;&amp;lt;/remarks&amp;gt;
    &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Public Shared Sub &lt;/SPAN&gt;SetPrimaryKey(&lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;trans &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;SqlCeTransaction, _
                                    &lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;e &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;SqlCeRowUpdatedEventArgs)

        &lt;SPAN style="COLOR: green"&gt;' If this is an INSERT operation...
        &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;If &lt;/SPAN&gt;e.Status = UpdateStatus.Continue &lt;SPAN style="COLOR: blue"&gt;AndAlso &lt;/SPAN&gt;_
           e.StatementType = StatementType.Insert &lt;SPAN style="COLOR: blue"&gt;Then
            Dim &lt;/SPAN&gt;pk = e.Row.Table.PrimaryKey
            &lt;SPAN style="COLOR: green"&gt;' and a primary key PK column exists...
            &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;If &lt;/SPAN&gt;pk &lt;SPAN style="COLOR: blue"&gt;IsNot Nothing AndAlso &lt;/SPAN&gt;pk.Count = 1 &lt;SPAN style="COLOR: blue"&gt;Then
                &lt;/SPAN&gt;&lt;SPAN style="COLOR: green"&gt;'Set up the post-update query to fetch new @@Identity
                &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Dim &lt;/SPAN&gt;cmdGetIdentity &lt;SPAN style="COLOR: blue"&gt;As New &lt;/SPAN&gt;SqlCeCommand(&lt;SPAN style="COLOR: #a31515"&gt;"SELECT @@IDENTITY"&lt;/SPAN&gt;, _
                                                       &lt;SPAN style="COLOR: blue"&gt;CType&lt;/SPAN&gt;(trans.Connection, SqlCeConnection), _
                                                       trans)
                
                &lt;SPAN style="COLOR: green"&gt;'Execute the command and set the result identity value to the PK
                &lt;/SPAN&gt;e.Row(pk(0)) = &lt;SPAN style="COLOR: blue"&gt;CInt&lt;/SPAN&gt;(cmdGetIdentity.ExecuteScalar)
                e.Row.AcceptChanges()

            &lt;SPAN style="COLOR: blue"&gt;End If
        End If
    End Sub
End Class

Namespace &lt;/SPAN&gt;MyDatabaseDataSetTableAdapters
    &lt;SPAN style="COLOR: blue"&gt;Partial Public Class &lt;/SPAN&gt;CategoriesTableAdapter
        &lt;SPAN style="COLOR: blue"&gt;Private Sub &lt;/SPAN&gt;_adapter_RowUpdated(&lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;sender &lt;SPAN style="COLOR: blue"&gt;As Object&lt;/SPAN&gt;, _
                                        &lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;e &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;SqlCeRowUpdatedEventArgs) _
                                        &lt;SPAN style="COLOR: blue"&gt;Handles &lt;/SPAN&gt;_adapter.RowUpdated

            SQLCEIDHelper.SetPrimaryKey(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.Transaction, e)
        &lt;SPAN style="COLOR: blue"&gt;End Sub
    End Class

    Partial Public Class &lt;/SPAN&gt;ProductsTableAdapter
        &lt;SPAN style="COLOR: blue"&gt;Private Sub &lt;/SPAN&gt;_adapter_RowUpdated(&lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;sender &lt;SPAN style="COLOR: blue"&gt;As Object&lt;/SPAN&gt;, _
                                        &lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;e &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;SqlCeRowUpdatedEventArgs) _
                                        &lt;SPAN style="COLOR: blue"&gt;Handles &lt;/SPAN&gt;_adapter.RowUpdated

            SQLCEIDHelper.SetPrimaryKey(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.Transaction, e)
        &lt;SPAN style="COLOR: blue"&gt;End Sub
    End Class
End Namespace

Partial Class &lt;/SPAN&gt;MyDatabaseDataSet
    &lt;SPAN style="COLOR: blue"&gt;Partial Class &lt;/SPAN&gt;CategoriesDataTable
        &lt;SPAN style="COLOR: blue"&gt;Private Sub &lt;/SPAN&gt;CategoriesDataTable_TableNewRow(&lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;sender &lt;SPAN style="COLOR: blue"&gt;As Object&lt;/SPAN&gt;, _
                                            &lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;e &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;System.Data.DataTableNewRowEventArgs) _
                                            &lt;SPAN style="COLOR: blue"&gt;Handles Me&lt;/SPAN&gt;.TableNewRow
            &lt;SPAN style="COLOR: green"&gt;'Set defaults so that constraints don't fail when EndEdit is called
            &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Dim &lt;/SPAN&gt;cat = &lt;SPAN style="COLOR: blue"&gt;CType&lt;/SPAN&gt;(e.Row, CategoriesRow)
            cat.CategoryName = &lt;SPAN style="COLOR: #a31515"&gt;"[new]"
        &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;End Sub
    End Class

    Partial Class &lt;/SPAN&gt;ProductsDataTable
        &lt;SPAN style="COLOR: blue"&gt;Private Sub &lt;/SPAN&gt;ProductsDataTable_TableNewRow(&lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;sender &lt;SPAN style="COLOR: blue"&gt;As Object&lt;/SPAN&gt;, _
                                             &lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;e &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;System.Data.DataTableNewRowEventArgs) _
                                             &lt;SPAN style="COLOR: blue"&gt;Handles Me&lt;/SPAN&gt;.TableNewRow
            &lt;SPAN style="COLOR: green"&gt;'Set defaults so that constraints don't fail when EndEdit is called
            &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Dim &lt;/SPAN&gt;product = &lt;SPAN style="COLOR: blue"&gt;CType&lt;/SPAN&gt;(e.Row, ProductsRow)
            product.ProductName = &lt;SPAN style="COLOR: #a31515"&gt;"[new]"
        &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;End Sub
    End Class
End Class&lt;/SPAN&gt;&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;Now when we run our form, click the Add button on the ToolStrip to add a new Category and then enter new Products in the DataGridView below. Click Save and you will see the identity keys refresh back into the DataTables from our SQL CE database. &lt;/P&gt;
&lt;P&gt;&lt;A href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_18.png" target=_blank mce_href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_18.png"&gt;&lt;IMG style="BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; DISPLAY: inline; BORDER-TOP: 0px; BORDER-RIGHT: 0px" title=image border=0 alt=image src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_thumb_8.png" width=580 height=333 mce_src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/InsertingMasterDetailDataintoaSQLServerC_C610/image_thumb_8.png"&gt;&lt;/A&gt; &lt;/P&gt;
&lt;P&gt;So to recap:&lt;/P&gt;
&lt;OL&gt;
&lt;LI&gt;Create your SQL CE tables, set the PKs to an Identity Integer column and then set up the relation to enforce referential integrity&lt;/LI&gt;
&lt;LI&gt;Create your DataSet and edit the relation and set it to a “Relation and Foreign Key Constraint” then set the Update and Delete rules to Cascade&lt;/LI&gt;
&lt;LI&gt;Make sure the PKs on the DataTables in the designer are set ReadOnly False&lt;/LI&gt;
&lt;LI&gt;Make sure to design your form so that the parent and &lt;EM&gt;related &lt;/EM&gt;children BindingSources are set up properly&lt;/LI&gt;
&lt;LI&gt;Call EndEdit on the ParentBindingSource before you attempt to insert any child rows into the child DataTable so that the parent row is committed to the parent DataTable&lt;/LI&gt;
&lt;LI&gt;Use the TableAdapterManager to handle updating parents and children in proper order (this happens by default if you use the designer)&lt;/LI&gt;
&lt;LI&gt;Add a handler to the DataAdapter’s RowUpdated event to query the database for the new identity (SELECT @@IDENTITY) and set the PK on the DataRow to that value and this will cascade to any related children automatically&lt;/LI&gt;&lt;/OL&gt;
&lt;P&gt;&lt;A href="http://code.msdn.microsoft.com/InsertSQLCE/" target=_blank mce_href="http://code.msdn.microsoft.com/InsertSQLCE/"&gt;&lt;STRONG&gt;Download the sample application from Code Gallery.&lt;/STRONG&gt;&lt;/A&gt;&lt;/P&gt;
&lt;P&gt;I hope that clears up the confusion on how to work with file-based databases like Access and SQL CE that don’t support batch statements. Once you understand how ADO.NET is working with your DataSets then it’s much easier to understand how to configure things like this. SQL CE is a great FREE database for single-user applications and I encourage you to have a look at it if you’re building these types of client applications. &lt;/P&gt;
&lt;P&gt;SQL CE also supports the Entity Framework so that would probably be a good follow-up post to this one… next time! ;-)&lt;/P&gt;
&lt;P&gt;Enjoy!&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9895646" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Visual+Basic/default.aspx">Visual Basic</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/VS2008/default.aspx">VS2008</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/SQL+Server/default.aspx">SQL Server</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/DevCenter/default.aspx">DevCenter</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Article/default.aspx">Article</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Data/default.aspx">Data</category></item><item><title>New “How Do I” Videos Released on Entity Framework &amp; WPF</title><link>http://blogs.msdn.com/bethmassi/archive/2009/08/26/new-how-do-i-videos-released-on-entity-framework-wpf.aspx</link><pubDate>Wed, 26 Aug 2009 20:18:08 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9885620</guid><dc:creator>Beth Massi</dc:creator><slash:comments>4</slash:comments><comments>http://blogs.msdn.com/bethmassi/comments/9885620.aspx</comments><wfw:commentRss>http://blogs.msdn.com/bethmassi/commentrss.aspx?PostID=9885620</wfw:commentRss><wfw:comment>http://blogs.msdn.com/bethmassi/rsscomments.aspx?PostID=9885620</wfw:comment><description>&lt;p&gt;Yesterday we released a couple more videos onto the &lt;a href="http://msdn.com/vbasic"&gt;Visual Basic Developer Center&lt;/a&gt; on building WPF data-entry forms with Entity Framework:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/vbasic/ee364700.aspx"&gt;How Do I: Hook Up and Display Validation in WPF using Entity Framework?&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/vbasic/ee364701.aspx"&gt;How Do I: Build a WPF Master-Detail Data Entry Form Using Entity Framework?&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;That makes 5 videos total on &lt;a href="http://msdn.microsoft.com/en-us/vbasic/bb466226.aspx#wpfentity"&gt;working with EF in WPF applications&lt;/a&gt;. Others released previously:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/vbasic/dd776537.aspx"&gt;How Do I: Get Started with Entity Framework in WPF Applications?&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/vbasic/dd776540.aspx"&gt;How Do I: Build a WPF Data Entry Form Using Entity Framework?&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/vbasic/dd776544.aspx"&gt;How Do I: Create a WPF Lookup Combobox using Entity Framework?&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;These videos are based on articles I’ve posted here in the past. So if you like reading better that watching videos here you go:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://blogs.msdn.com/bethmassi/archive/2009/04/30/data-binding-wpf-lookup-combobox-values-to-ef-entities.aspx"&gt;Data Binding WPF Lookup Combobox Values to EF Entities&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/bethmassi/archive/2009/05/04/notifying-the-ui-when-entity-references-change-in-lookup-comboboxes.aspx"&gt;Notifying the UI when Entity References Change in Lookup Comboboxes&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/bethmassi/archive/2009/05/08/using-the-wpf-observablecollection-with-ef-entities.aspx"&gt;Using the WPF ObservableCollection with EF Entities&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/bethmassi/archive/2009/07/07/implementing-validation-in-wpf-on-entity-framework-entities.aspx"&gt;Implementing Validation in WPF on Entity Framework Entities&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/bethmassi/archive/2009/07/14/master-detail-data-binding-in-wpf-with-entity-framework.aspx"&gt;Master-Detail Data Binding in WPF with Entity Framework&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/bethmassi/archive/2009/07/16/filtering-entity-framework-collections-in-master-detail-forms.aspx"&gt;Filtering Entity Framework Collections in Master-Detail Forms&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;There are also additional resources listed on the How Do I video pages themselves pointing to topics in the MSDN Library.&lt;/p&gt;  &lt;p&gt;Enjoy!&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9885620" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Visual+Basic/default.aspx">Visual Basic</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/WPF/default.aspx">WPF</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/VS2008/default.aspx">VS2008</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Videos/default.aspx">Videos</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/DevCenter/default.aspx">DevCenter</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Data/default.aspx">Data</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Entity+Framework/default.aspx">Entity Framework</category></item><item><title>N-Tier Application Patterns with Entity Framework</title><link>http://blogs.msdn.com/bethmassi/archive/2009/08/05/n-tier-application-patterns-with-entity-framework.aspx</link><pubDate>Thu, 06 Aug 2009 01:20:52 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9858455</guid><dc:creator>Beth Massi</dc:creator><slash:comments>5</slash:comments><comments>http://blogs.msdn.com/bethmassi/comments/9858455.aspx</comments><wfw:commentRss>http://blogs.msdn.com/bethmassi/commentrss.aspx?PostID=9858455</wfw:commentRss><wfw:comment>http://blogs.msdn.com/bethmassi/rsscomments.aspx?PostID=9858455</wfw:comment><description>&lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/magazine/ee310078.aspx" target="_blank"&gt;This month’s MSDN Magazine&lt;/a&gt; has a particularly good article in there by &lt;a href="http://blogs.msdn.com/dsimmons" target="_blank"&gt;Danny Simmons&lt;/a&gt;, Development Manager on the Entity Framework team, on &lt;a href="http://msdn.microsoft.com/en-us/magazine/ee321569.aspx" target="_blank"&gt;&lt;strong&gt;N-Tier Application Patterns with Entity Framework&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt;&amp;#160;&lt;/strong&gt;that I recommend reading through. He explains the design considerations you need to take into account when building n-tier applications and also discusses some of the improvements that are coming in .NET Framework 4.0 that will make building n-tier applications with EF much much easier. I’m personally looking forward to self-tracking entities myself, hooray! &lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/adonet" target="_blank"&gt;Tim Mallalieu&lt;/a&gt; also has a good &lt;a href="http://msdn.microsoft.com/en-us/magazine/ee236639.aspx" target="_blank"&gt;best practices article&lt;/a&gt; in this issue that I just started digging into regarding the next version of Entity Framework. &lt;/p&gt;  &lt;p&gt;Enjoy!&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9858455" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Data/default.aspx">Data</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/N-tier/default.aspx">N-tier</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Entity+Framework/default.aspx">Entity Framework</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/VS2010/default.aspx">VS2010</category></item><item><title>Working with a Local Database File in Visual Studio</title><link>http://blogs.msdn.com/bethmassi/archive/2009/07/31/working-with-a-local-database-file-in-visual-studio.aspx</link><pubDate>Fri, 31 Jul 2009 22:58:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9854660</guid><dc:creator>Beth Massi</dc:creator><slash:comments>4</slash:comments><comments>http://blogs.msdn.com/bethmassi/comments/9854660.aspx</comments><wfw:commentRss>http://blogs.msdn.com/bethmassi/commentrss.aspx?PostID=9854660</wfw:commentRss><wfw:comment>http://blogs.msdn.com/bethmassi/rsscomments.aspx?PostID=9854660</wfw:comment><description>&lt;P&gt;In &lt;A href="http://blogs.msdn.com/bethmassi/archive/2007/05/29/working-with-a-local-data-file-in-vs.aspx" target=_blank mce_href="http://blogs.msdn.com/bethmassi/archive/2007/05/29/working-with-a-local-data-file-in-vs.aspx"&gt;this post&lt;/A&gt; and &lt;A href="http://msdn2.microsoft.com/en-us/vbasic/bb643822.aspx" target=_blank mce_href="http://msdn2.microsoft.com/en-us/vbasic/bb643822.aspx"&gt;video&lt;/A&gt; I’ve shown folks how to work with a local database file (.mdf, .mdb, .sdf) that resides directly inside your project in order to see updates made while debugging your application. If it looks like everything saves fine while debugging, but you can’t see the updates if you look directly in the database, then there’s a simple fix. Today the VS Data Team wrote up a &lt;A href="http://blogs.msdn.com/vsdata/archive/2009/07/31/debugging-with-local-database-file.aspx" target=_blank mce_href="http://blogs.msdn.com/vsdata/archive/2009/07/31/debugging-with-local-database-file.aspx"&gt;great blog post&lt;/A&gt; on this as well so check it out! &lt;/P&gt;
&lt;P&gt;In general I prefer to develop against attached SQL Server databases because it’s easier to debug. But if you’re working with SQL Compact or Access databases you’ll need to be aware of how the database file is copied out with your application EXE and what file you are really working with. &lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;A href="http://blogs.msdn.com/vsdata/archive/2009/07/31/debugging-with-local-database-file.aspx"&gt;&lt;STRONG&gt;&lt;FONT color=#006bad&gt;VSData Team Blog: Debugging with Local Database File&lt;/FONT&gt;&lt;/STRONG&gt;&lt;/A&gt; 
&lt;LI&gt;&lt;A href="http://blogs.msdn.com/bethmassi/archive/2007/05/29/working-with-a-local-data-file-in-vs.aspx" target=_blank&gt;&lt;FONT color=#006bad&gt;This (My)&amp;nbsp;Blog: Working with a Local Data File in VS&lt;/FONT&gt;&lt;/A&gt; 
&lt;LI&gt;&lt;A href="http://msdn.microsoft.com/en-us/vbasic/bb643822.aspx" target=_blank&gt;&lt;FONT color=#006bad&gt;Dev Center Video: How Do I Work with Local Data?&lt;/FONT&gt;&lt;/A&gt; 
&lt;LI&gt;&lt;A href="http://msdn.microsoft.com/en-us/library/ms246989.aspx" target=_blank&gt;&lt;FONT color=#006bad&gt;MSDN Library: How to Manage Local Data Files in Your Project&lt;/FONT&gt;&lt;/A&gt;&lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;Enjoy!&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9854660" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/bethmassi/archive/tags/VS2005/default.aspx">VS2005</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/VS2008/default.aspx">VS2008</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/DevCenter/default.aspx">DevCenter</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Data/default.aspx">Data</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/VS2010/default.aspx">VS2010</category></item><item><title>Filtering Child DataTables Using TableAdapters</title><link>http://blogs.msdn.com/bethmassi/archive/2009/07/22/filtering-child-datatables-using-tableadapters.aspx</link><pubDate>Thu, 23 Jul 2009 03:02:53 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9845448</guid><dc:creator>Beth Massi</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/bethmassi/comments/9845448.aspx</comments><wfw:commentRss>http://blogs.msdn.com/bethmassi/commentrss.aspx?PostID=9845448</wfw:commentRss><wfw:comment>http://blogs.msdn.com/bethmassi/rsscomments.aspx?PostID=9845448</wfw:comment><description>&lt;p&gt;Since my &lt;a href="http://blogs.msdn.com/bethmassi/archive/2009/07/16/filtering-entity-framework-collections-in-master-detail-forms.aspx" target="_blank"&gt;last post on filtering child collections using Entity Framework&lt;/a&gt;, I have had more than a few emails about how to load filtered child DataTables that are part of a master-detail relationship and then get them to save properly through the TableAdapters. Many people are running into the problem where the designer won’t automatically generate the update/insert/delete commands for you when you are writing a select statement that uses multiple tables. Of course you could specify your own statements manually (and often you need to because your Select statement is too complex) but in this case there’s a &lt;strong&gt;much better way &lt;/strong&gt;to specify this filter and still get the benefit of the designer creating your commands.&lt;/p&gt;  &lt;p&gt;For instance, let’s take the same database tables Customer and Orders that we’ve been working with:&lt;/p&gt;  &lt;p&gt;&lt;img src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/DataBindingWPFLookupComboboxValuestoEFEn_F345/image_thumb.png" /&gt; &lt;/p&gt;  &lt;p&gt;NOTE: If you are unfamiliar with how to set up and work with master-detail (parent-child) tables &lt;a href="http://msdn.microsoft.com/en-us/vbasic/cc138241.aspx" target="_blank"&gt;check out this &amp;quot;How Do I&amp;quot; video&lt;/a&gt;&lt;strong&gt;&lt;/strong&gt; first.&lt;/p&gt;  &lt;p&gt;So say we want to only pull up the Orders on the Customer who’s LastName is “Massi” -- meaning we want to filter &lt;em&gt;both &lt;/em&gt;the parent (Customer) and child (Orders) on Customer.LastName. There’s a couple ways to do this. &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Specifying a New Query &lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;TableAdapters are great at managing your queries. By default when you use the designer to select related tables it will automatically create default Fill and GetData select methods for you as well as generate the update//insert and delete statements for you. If you look in the properties for the TableAdapter you will see a SelectCommand generated for you that selects ALL the fields and ALL the rows of the table in the database. In 99.999% of the cases you want to filter these rows for scalability reasons. (And I urge you to do so). &lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/FilteringChildDataTablesUsingTableAdapte_CC44/image_4.png"&gt;&lt;img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="342" alt="image" src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/FilteringChildDataTablesUsingTableAdapte_CC44/image_thumb_1.png" width="652" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Also notice that Visual Studio has created Insert/Update/Delete commands as well for us. We can easily specify a new query that filters our rows and still take advantage of these update/insert/delete commands. We want to do this for both our tables.&lt;/p&gt;  &lt;p&gt;First right-click on the child TableAdapter (in this case OrdersTableAdapter) and select Add –&amp;gt; Query. Then choose your command type, here I’ll leave the default “Use SQL Statements”. Click Next. Then choose your query type, in this case choose the default “SELECT which returns rows”. Click Next. Now you can write your select statement. &lt;/p&gt;  &lt;p&gt;It is &lt;strong&gt;VERY IMPORTANT &lt;/strong&gt;that you only select the fields from the child (Orders) table and not include fields from other tables in the result set. Otherwise the generated commands will not work. You can filter the rows any way you like with a WHERE clause (and you definitely should) but keep in mind that if you select fields from other tables to be included in the result set, then you will need to specify your own Insert\Update\Delete commands above.&lt;/p&gt;  &lt;p&gt;To write our filter on the child Orders table I’ll use the command builder to join the Customer table and then use the LastName in the WHERE clause.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/FilteringChildDataTablesUsingTableAdapte_CC44/image_6.png"&gt;&lt;img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="610" alt="image" src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/FilteringChildDataTablesUsingTableAdapte_CC44/image_thumb_2.png" width="598" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Here’ I’m creating a &lt;strong&gt;parameterized query &lt;/strong&gt;so that I can specify the LastName on the Form and not hard-code it here. Notice that the structure of the result set (the fields in the SELECT clause above) exactly match the fields in the OrdersDataTable. &lt;/p&gt;  &lt;p&gt;&lt;font face="Courier New" size="2"&gt;SELECT&amp;#160; Orders.OrderID,&amp;#160; &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Orders.CustomerID,       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Orders.OrderDate,       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Orders.ShipDate,       &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Orders.Modified      &lt;br /&gt;FROM&amp;#160;&amp;#160;&amp;#160; Orders INNER JOIN      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; Customer ON Orders.CustomerID = Customer.CustomerID      &lt;br /&gt;WHERE&amp;#160; (Customer.LastName = @LastName)&lt;/font&gt;&lt;/p&gt;  &lt;p&gt;Click OK to get out of the Query Builder (if you were in there) and then Click Next. Now you get to choose which methods to generate and what they should be named. For this example I named them FillByLastName and GetDataByLastName. This creates methods on the TableAdapter that you can now use to query the child rows.&lt;/p&gt;  &lt;p&gt;Now repeat this process for the parent table (Customer). Select the CustomerTableAdapter in the dataset designer, right-click and select Add –&amp;gt; Query. Same steps as before except the SELECT statement is much easier, no JOIN necessary, just a filtered WHERE clause.&lt;/p&gt;  &lt;p&gt;&lt;font face="Courier New" size="2"&gt;SELECT CustomerID, LastName, FirstName, Address, City, State, ZIP, Modified      &lt;br /&gt;FROM&amp;#160;&amp;#160; Customer       &lt;br /&gt;WHERE&amp;#160; LastName = @LastName&lt;/font&gt;&lt;/p&gt;  &lt;p&gt;I named the methods the same as I did for the child, FillByLastName and GetDataByLastName. &lt;/p&gt;  &lt;p&gt;Now you can design your master-detail form. From the Data Sources Window expand and then drag the parent (Customer) and then drag the related Orders (the one under Customer) onto your Windows form. Basically design your winform like normal and let Visual Studio generate the code to load and save for you.&lt;/p&gt;  &lt;p&gt;The only thing you have to do now is change the method names on the TableAdapters (and make sure they load in parent then child order) in the form Load handler:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Private Sub &lt;/span&gt;Form1_Load() &lt;span style="color: blue"&gt;Handles MyBase&lt;/span&gt;.Load
    &lt;span style="color: blue"&gt;Me&lt;/span&gt;.CustomerTableAdapter.FillByLastName(&lt;span style="color: blue"&gt;Me&lt;/span&gt;.OMSDataSet.Customer, &lt;span style="color: #a31515"&gt;&amp;quot;Massi&amp;quot;&lt;/span&gt;)
    &lt;span style="color: blue"&gt;Me&lt;/span&gt;.OrdersTableAdapter.FillByLastName(&lt;span style="color: blue"&gt;Me&lt;/span&gt;.OMSDataSet.Orders, &lt;span style="color: #a31515"&gt;&amp;quot;Massi&amp;quot;&lt;/span&gt;)
&lt;span style="color: blue"&gt;End Sub&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Everything else will work like before but now we are filtering both the tables. You can add as many new queries to the TableAdapters as you need. As long as the fields in your query (SELECT clause) match the structure of your generated DataTable then you can use the generated update/insert/delete commands. &lt;/p&gt;

&lt;p&gt;But what if you already have hundreds of forms that use the default Fill or GetData methods and you really need to set up a filter on these SelectCommands because you don’t want to have to change all your forms? That’s pretty easy too.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Filtering the Default GetData and Fill Methods&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If we want to modify the default Fill and GetData methods to support this filter then there’s a little trick we can do. Once the DataSet is set up with your “unfiltered” parent-child tables, open up the properties window and expand the SelectCommand (like pictured above) and edit the CommandText property for both of the TableAdapters. Specify the same select statements as above. Once you modify the property Visual Studio will ask you “Do you want to regenerate updating commands based on the new command text? (Current updating commands will be overwritten)”. Just say &lt;strong&gt;NO&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;Now the calls to GetData and Fill will have a filter set but the generated commands will not be overwritten!&lt;/p&gt;

&lt;p&gt;I hope this clears things up for folks. Remember that it’s &lt;strong&gt;best practice to put filters on your queries &lt;/strong&gt;to narrow your result sets – this puts a lot less strain on your databases and networks. There’s a couple tricks you need up your sleeve to do this in Visual Studio, but it is the way it is so that the dataset designer can handle complex and completely custom scenarios too, like multi-table views and stored procedures. Hmmm… maybe it’s time for a How Do I video on that…. ;-)&lt;/p&gt;

&lt;p&gt;Enjoy!&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9845448" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Visual+Basic/default.aspx">Visual Basic</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/VS2008/default.aspx">VS2008</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/DevCenter/default.aspx">DevCenter</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Article/default.aspx">Article</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Data/default.aspx">Data</category></item><item><title>Master-Detail Data Binding in WPF with Entity Framework</title><link>http://blogs.msdn.com/bethmassi/archive/2009/07/14/master-detail-data-binding-in-wpf-with-entity-framework.aspx</link><pubDate>Wed, 15 Jul 2009 02:24:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9833642</guid><dc:creator>Beth Massi</dc:creator><slash:comments>16</slash:comments><comments>http://blogs.msdn.com/bethmassi/comments/9833642.aspx</comments><wfw:commentRss>http://blogs.msdn.com/bethmassi/commentrss.aspx?PostID=9833642</wfw:commentRss><wfw:comment>http://blogs.msdn.com/bethmassi/rsscomments.aspx?PostID=9833642</wfw:comment><description>&lt;P&gt;Today I thought I would talk about a really common scenario in data applications, creating a master-details (one-to-many) data entry form. I’ve written about WPF data binding and Entity Framework a lot in the past:&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Posts:&lt;/STRONG&gt;&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;A href="http://blogs.msdn.com/bethmassi/archive/2008/12/10/master-details-with-entity-framework-explicit-load.aspx" mce_href="http://blogs.msdn.com/bethmassi/archive/2008/12/10/master-details-with-entity-framework-explicit-load.aspx"&gt;Master-Details with Entity Framework Explicit Load&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://blogs.msdn.com/bethmassi/archive/2008/11/07/loading-data-and-binding-controls-in-wpf-with-collectionviewsource.aspx" mce_href="http://blogs.msdn.com/bethmassi/archive/2008/11/07/loading-data-and-binding-controls-in-wpf-with-collectionviewsource.aspx"&gt;Loading Data and Binding Controls in WPF with CollectionViewSource&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://blogs.msdn.com/bethmassi/archive/2009/05/08/using-the-wpf-observablecollection-with-ef-entities.aspx" mce_href="http://blogs.msdn.com/bethmassi/archive/2009/05/08/using-the-wpf-observablecollection-with-ef-entities.aspx"&gt;Using the WPF ObservableCollection with EF Entities&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://blogs.msdn.com/bethmassi/archive/2009/04/30/data-binding-wpf-lookup-combobox-values-to-ef-entities.aspx" target=_blank mce_href="http://blogs.msdn.com/bethmassi/archive/2009/04/30/data-binding-wpf-lookup-combobox-values-to-ef-entities.aspx"&gt;Data Binding WPF Lookup Combobox Values to EF Entities&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://blogs.msdn.com/bethmassi/archive/2009/05/04/notifying-the-ui-when-entity-references-change-in-lookup-comboboxes.aspx" mce_href="http://blogs.msdn.com/bethmassi/archive/2009/05/04/notifying-the-ui-when-entity-references-change-in-lookup-comboboxes.aspx"&gt;Notifying the UI when Entity References Change in Lookup Comboboxes&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://blogs.msdn.com/bethmassi/archive/2009/07/07/implementing-validation-in-wpf-on-entity-framework-entities.aspx" mce_href="http://blogs.msdn.com/bethmassi/archive/2009/07/07/implementing-validation-in-wpf-on-entity-framework-entities.aspx"&gt;Implementing Validation in WPF on Entity Framework Entities&lt;/A&gt;&lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;&lt;STRONG&gt;Videos:&lt;/STRONG&gt;&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;A href="http://msdn.microsoft.com/en-us/vbasic/dd776537.aspx" mce_href="http://msdn.microsoft.com/en-us/vbasic/dd776537.aspx"&gt;How Do I: Get Started with Entity Framework in WPF Applications?&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://msdn.microsoft.com/en-us/vbasic/dd776540.aspx" mce_href="http://msdn.microsoft.com/en-us/vbasic/dd776540.aspx"&gt;How Do I: Build a WPF Data Entry Form Using Entity Framework?&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://msdn.microsoft.com/en-us/vbasic/dd776544.aspx" mce_href="http://msdn.microsoft.com/en-us/vbasic/dd776544.aspx"&gt;How Do I: Create a WPF Lookup Combobox using Entity Framework?&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://msdn.microsoft.com/en-us/vbasic/dd239277.aspx" mce_href="http://msdn.microsoft.com/en-us/vbasic/dd239277.aspx"&gt;How Do I: Create a Master-Detail Data Entry Form in WPF?&lt;/A&gt;&lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;Today I want to pull these concepts together and walk through one way to create a master-detail form in WPF using entities from the Entity Framework. Specifically, we’ll declare CollectionViewSources in our XAML &lt;A href="http://blogs.msdn.com/bethmassi/archive/2008/11/07/loading-data-and-binding-controls-in-wpf-with-collectionviewsource.aspx" target=_blank mce_href="http://blogs.msdn.com/bethmassi/archive/2008/11/07/loading-data-and-binding-controls-in-wpf-with-collectionviewsource.aspx"&gt;like I showed here&lt;/A&gt;, to bind to an ObservableCollection of entities &lt;A href="http://blogs.msdn.com/bethmassi/archive/2009/05/08/using-the-wpf-observablecollection-with-ef-entities.aspx" target=_blank mce_href="http://blogs.msdn.com/bethmassi/archive/2009/05/08/using-the-wpf-observablecollection-with-ef-entities.aspx"&gt;like I showed here&lt;/A&gt;, where the children are explicitly loaded &lt;A href="http://blogs.msdn.com/bethmassi/archive/2008/12/10/master-details-with-entity-framework-explicit-load.aspx" target=_blank mce_href="http://blogs.msdn.com/bethmassi/archive/2008/12/10/master-details-with-entity-framework-explicit-load.aspx"&gt;like I showed here&lt;/A&gt;. Everybody got that? ;-)&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Creating the Entity Data Model&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;First let’s create a simple Entity Data Model (EDM) that demonstrates a Master-Detail relationship. I’ll use a simple database called OMS that has Customer and Orders tables with a non-nullable foreign key set up between them on CustomerID, meaning that no Order can exist without a Customer. This relationship is inferred by Entity Framework (EF) to set up the navigation properties. Notice that there is an Orders EntityCollection on Customer. &lt;/P&gt;
&lt;P&gt;&lt;IMG src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/DataBindingWPFLookupComboboxValuestoEFEn_F345/image_6.png" mce_src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/DataBindingWPFLookupComboboxValuestoEFEn_F345/image_6.png"&gt; &lt;/P&gt;
&lt;P&gt;What we want to do is build a simple form that will let us Edit, Add, and Delete Customers and their Orders. First let’s set up the WPF Data Binding in XAML. &lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Defining the CollectionViewSource and Data Bindings &lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;To recap, a CollectionViewSource is a proxy for the CollectionView which manages the currency (the position) in the list of entities. It has a property called &lt;EM&gt;Source&lt;/EM&gt; which can be set in our code behind. This way, we can set up CollectionVieSources in XAML for all our data lists and bind them to the corresponding controls all in XAML. Then at runtime in our code we set the Source properties and only at that time does the data pull from the database. &lt;/P&gt;
&lt;P&gt;To define a Master-Detail relationship we define two CollectionViewSources one for the master and one for the detail collections. Then on the detail we set the Source property to the master CollectionViewSource and then specify the Path property as the name of the child collection. In our case the name of the collection on Customer is “Orders”. So we can specify the XAML like so:&lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;&amp;lt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;Window.Resources&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;&amp;gt;
    &amp;lt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;CollectionViewSource &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;x&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;:&lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Key&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="MasterViewSource" /&amp;gt;
    &amp;lt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;CollectionViewSource &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;x&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;:&lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Key&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="DetailsViewSource" 
                    &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Source&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="{&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;Binding &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Source&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;={&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;StaticResource &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;MasterViewSource&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;}, &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Path&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;='Orders'}" /&amp;gt;
&amp;lt;/&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;Window.Resources&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;&amp;gt;&lt;/SPAN&gt;&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;Now as the position changes in the MasterViewSource to point to a new Customer, the DetailsViewSource will filter automatically to only those related Orders for that Customer. We can now set the rest of the data bindings on the controls on the form by setting the BindingContext of the container controls to the CollectionViewSource we want to display. For example, we can set up a StackPanel to contain the Customer fields and set the StackPanel.DataContext to the MasterViewSource. Under that we can set up a ListView to display the Orders by setting the ListView.ItemsSource to the DetailsViewSource.&lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;&amp;lt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;Grid&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;&amp;gt;
&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;...&lt;BR&gt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;    &amp;lt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;StackPanel &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Name&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="StackPanel2" &lt;BR&gt;                &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Grid.Column&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="1" &lt;BR&gt;                &lt;/SPAN&gt;&lt;STRONG&gt;&lt;SPAN style="COLOR: red"&gt;DataContext&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="{&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;Binding &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Source&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;={&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;StaticResource &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;MasterViewSource&lt;/SPAN&gt;&lt;/STRONG&gt;&lt;SPAN style="COLOR: blue"&gt;&lt;STRONG&gt;}&lt;/STRONG&gt;}"&amp;gt;
        &amp;lt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;TextBox &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Name&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="TextBox1" &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;IsReadOnly&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="True" 
                 &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Text&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="{&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;Binding &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Path&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;=CustomerID, &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Mode&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;=OneWay}"/&amp;gt;
        &amp;lt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;TextBox &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Name&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="TextBox5"&lt;BR&gt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;                 Text&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="{&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;Binding &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Path&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;=LastName}"/&amp;gt;&lt;BR&gt;...
&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;    &amp;lt;/&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;StackPanel&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;&amp;gt;
...&lt;BR&gt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;    &amp;lt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;ListView &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Grid.Row&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="3" &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Name&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="ListView1" 
              &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;IsSynchronizedWithCurrentItem&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="True"
&lt;STRONG&gt;              &lt;/STRONG&gt;&lt;/SPAN&gt;&lt;STRONG&gt;&lt;SPAN style="COLOR: red"&gt;ItemsSource&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="{&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;Binding &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Source&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;={&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;StaticResource &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;DetailsViewSource&lt;/SPAN&gt;&lt;/STRONG&gt;&lt;SPAN style="COLOR: blue"&gt;&lt;STRONG&gt;}}"&amp;gt;
&lt;/STRONG&gt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;        &amp;lt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;ListView.View&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;&amp;gt;
            &amp;lt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;GridView&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;&amp;gt;
                &amp;lt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;GridViewColumn &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Header&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="ID" &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Width&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="75"&amp;gt;
                    &amp;lt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;GridViewColumn.CellTemplate&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;&amp;gt;
                        &amp;lt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;DataTemplate&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;&amp;gt;
                        &amp;lt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;Label &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Content&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="{&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;Binding &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Path&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;=OrderID}" 
                                     &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Margin&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="-6,0,-6,0"/&amp;gt;
                        &amp;lt;/&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;DataTemplate&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;&amp;gt;
                    &amp;lt;/&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;GridViewColumn.CellTemplate&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;&amp;gt;
                &amp;lt;/&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;GridViewColumn&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;&amp;gt;
                &amp;lt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;GridViewColumn &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Header&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="Order Date" &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Width&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="100"&amp;gt;
                    &amp;lt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;GridViewColumn.CellTemplate&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;&amp;gt;
                        &amp;lt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;DataTemplate&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;&amp;gt;
                            &amp;lt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;TextBox &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Text&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="{&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;Binding &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Path&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;=OrderDate}" 
                                     &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Margin&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="-6,0,-6,0"/&amp;gt;
                        &amp;lt;/&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;DataTemplate&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;&amp;gt;
                    &amp;lt;/&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;GridViewColumn.CellTemplate&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;&amp;gt;
                &amp;lt;/&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;GridViewColumn&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;&amp;gt;
...&lt;/SPAN&gt;&lt;/PRE&gt;
&lt;P&gt;The only thing we need to do now is set the Source property of the MasterViewSource in code to the collection of our Customer entities. &lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Defining the Master-Detail Entities in an ObservableCollection&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;I showed before how we can create a collection of entities that inherits from ObservableCollection &lt;A href="http://blogs.msdn.com/bethmassi/archive/2009/05/08/using-the-wpf-observablecollection-with-ef-entities.aspx" target=_blank mce_href="http://blogs.msdn.com/bethmassi/archive/2009/05/08/using-the-wpf-observablecollection-with-ef-entities.aspx"&gt;in this post&lt;/A&gt; to make it easier to work with WPF data binding. But in that example we were only working with a simple collection of Customers and not their Orders. If you recall, the ObjectContext is what tracks changes on entities so in order for the ObjectContext to be notified that adds and deletes to the ObservableCollection need to be tracked you need to override the InsertItem and RemoveItem methods so that you can tell the ObjectContext to either add or delete the entity which will ultimately execute against the database. In the constructor I pass a reference to the ObjectContext. You can also pass in any collection of entities, say from a LINQ query, and then add them to the ObservableCollection. However, we need to make a couple modifications to our collection so that we can also track the child order entities correctly. &lt;/P&gt;
&lt;P&gt;Adds to the Customer.Orders EntityCollection will will cause the addition of a new Order to the collection as well as the association to Customer automatically. However removing the Order from the Customer.Orders EntityCollection will only &lt;EM&gt;remove the association &lt;/EM&gt;and will not attempt to actually delete the Order from the database. Instead it attempts to set the CustomerID to NULL (to remove the association from the Customer) but since we have referential integrity set up to disallow this we will get an error if we attempt to SaveChanges. &lt;/P&gt;
&lt;P&gt;In a lot of scenarios it makes sense to just remove the association and set the foreign key to NULL in the database. But in this example we really mean to delete the Order record completely when the Order is removed from the collection. So the key is adding an event handler to the AssociationChanged event on the Orders EntityCollection that’s hanging off our Customer entity and telling the ObjectContext to explicitly delete the Order. &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;Public Class &lt;/SPAN&gt;CustomerCollection
    &lt;SPAN style="COLOR: blue"&gt;Inherits &lt;/SPAN&gt;ObservableCollection(&lt;SPAN style="COLOR: blue"&gt;Of &lt;/SPAN&gt;Customer)

    &lt;SPAN style="COLOR: blue"&gt;Private &lt;/SPAN&gt;_context &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;OMSEntities
    &lt;SPAN style="COLOR: blue"&gt;Public ReadOnly Property &lt;/SPAN&gt;Context() &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;OMSEntities
        &lt;SPAN style="COLOR: blue"&gt;Get
            Return &lt;/SPAN&gt;_context
        &lt;SPAN style="COLOR: blue"&gt;End Get
    End Property


    Sub New&lt;/SPAN&gt;(&lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;customers &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;IEnumerable(&lt;SPAN style="COLOR: blue"&gt;Of &lt;/SPAN&gt;Customer), &lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;context &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;OMSEntities)
        &lt;SPAN style="COLOR: blue"&gt;MyBase&lt;/SPAN&gt;.New(customers)
        _context = context

        &lt;SPAN style="COLOR: blue"&gt;For Each &lt;/SPAN&gt;c &lt;SPAN style="COLOR: blue"&gt;In &lt;/SPAN&gt;customers
            &lt;SPAN style="COLOR: blue"&gt;AddHandler &lt;/SPAN&gt;c.Orders.AssociationChanged, &lt;SPAN style="COLOR: blue"&gt;AddressOf &lt;/SPAN&gt;Orders_CollectionChanged
        &lt;SPAN style="COLOR: blue"&gt;Next
    End Sub

    Protected Overrides Sub &lt;/SPAN&gt;InsertItem(&lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;index &lt;SPAN style="COLOR: blue"&gt;As Integer&lt;/SPAN&gt;, &lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;item &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;Customer)
        &lt;SPAN style="COLOR: blue"&gt;AddHandler &lt;/SPAN&gt;item.Orders.AssociationChanged, &lt;SPAN style="COLOR: blue"&gt;AddressOf &lt;/SPAN&gt;Orders_CollectionChanged

        &lt;SPAN style="COLOR: green"&gt;'Tell the ObjectContext to start tracking this customer entity
        &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.Context.AddToCustomers(item)
        &lt;SPAN style="COLOR: blue"&gt;MyBase&lt;/SPAN&gt;.InsertItem(index, item)
    &lt;SPAN style="COLOR: blue"&gt;End Sub

    Protected Overrides Sub &lt;/SPAN&gt;RemoveItem(&lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;index &lt;SPAN style="COLOR: blue"&gt;As Integer&lt;/SPAN&gt;)
        &lt;SPAN style="COLOR: blue"&gt;Dim &lt;/SPAN&gt;customer = &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;(index)
        &lt;SPAN style="COLOR: blue"&gt;RemoveHandler &lt;/SPAN&gt;customer.Orders.AssociationChanged, &lt;SPAN style="COLOR: blue"&gt;AddressOf &lt;/SPAN&gt;Orders_CollectionChanged

        &lt;SPAN style="COLOR: blue"&gt;For &lt;/SPAN&gt;i = customer.Orders.Count - 1 &lt;SPAN style="COLOR: blue"&gt;To &lt;/SPAN&gt;0 &lt;SPAN style="COLOR: blue"&gt;Step &lt;/SPAN&gt;-1
            &lt;SPAN style="COLOR: green"&gt;'When deleting a customer, delete any orders if any exist
            &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.Context.DeleteObject(customer.Orders(i))
        &lt;SPAN style="COLOR: blue"&gt;Next

        &lt;/SPAN&gt;&lt;SPAN style="COLOR: green"&gt;'Tell the ObjectContext to delete this customer entity
        &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.Context.DeleteObject(customer)
        &lt;SPAN style="COLOR: blue"&gt;MyBase&lt;/SPAN&gt;.RemoveItem(index)
    &lt;SPAN style="COLOR: blue"&gt;End Sub

    Private Sub &lt;/SPAN&gt;Orders_CollectionChanged(&lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;sender &lt;SPAN style="COLOR: blue"&gt;As Object&lt;/SPAN&gt;, _
                                         &lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;e &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;CollectionChangeEventArgs)
        &lt;SPAN style="COLOR: blue"&gt;If &lt;/SPAN&gt;e.Action = CollectionChangeAction.Remove &lt;SPAN style="COLOR: blue"&gt;Then
            &lt;/SPAN&gt;&lt;SPAN style="COLOR: green"&gt;'Adding an order to a customer is handled automatically 
            ' for us but we need to tell the ObjectContext to delete the order
            ' if an order is removed from the Orders EntityCollection 
           &lt;STRONG&gt; &lt;/STRONG&gt;&lt;/SPAN&gt;&lt;STRONG&gt;&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.Context.DeleteObject(&lt;SPAN style="COLOR: blue"&gt;CType&lt;/SPAN&gt;(e.Element, Order))&lt;/STRONG&gt;
        &lt;SPAN style="COLOR: blue"&gt;End If
    End Sub
End Class
&lt;/SPAN&gt;&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;&lt;STRONG&gt;Loading the Master-Detail Entities &lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;Finally we’re ready to write a LINQ query to load the entities into our CustomerCollection and then set that as the Source property of the MasterViewSource. In this example I’m loading the Orders explicitly by calling .Include(“Orders”) on the LINQ query which constructs a single statement to retrieve the Customer and all their Orders from the database. &lt;A href="http://blogs.msdn.com/bethmassi/archive/2008/12/10/master-details-with-entity-framework-explicit-load.aspx" target=_blank mce_href="http://blogs.msdn.com/bethmassi/archive/2008/12/10/master-details-with-entity-framework-explicit-load.aspx"&gt;I discuss explicit load in this post&lt;/A&gt;. &lt;/P&gt;
&lt;P&gt;We can then grab a reference to the MasterViewSource &amp;amp; DetailViewSource’s View property in order to add/remove items in the collections. When we’re done, we can call SaveChanges on the ObjectContext and the database will be updated. &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;Private &lt;/SPAN&gt;db &lt;SPAN style="COLOR: blue"&gt;As New &lt;/SPAN&gt;OMSEntities &lt;SPAN style="COLOR: green"&gt;'EF ObjectContext connects to database and tracks changes
&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Private &lt;/SPAN&gt;CustomerData &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;CustomerCollection &lt;SPAN style="COLOR: green"&gt;'inherits from ObservableCollection

&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Private &lt;/SPAN&gt;MasterViewSource &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;CollectionViewSource
&lt;SPAN style="COLOR: blue"&gt;Private &lt;/SPAN&gt;DetailViewSource &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;CollectionViewSource

&lt;SPAN style="COLOR: green"&gt;'provides currency to controls (position &amp;amp; movement in the collections)
&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Private WithEvents &lt;/SPAN&gt;MasterView &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;ListCollectionView
&lt;SPAN style="COLOR: blue"&gt;Private &lt;/SPAN&gt;DetailsView &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;BindingListCollectionView

&lt;SPAN style="COLOR: blue"&gt;Private Sub &lt;/SPAN&gt;Window_Loaded() &lt;SPAN style="COLOR: blue"&gt;Handles MyBase&lt;/SPAN&gt;.Loaded

    &lt;SPAN style="COLOR: blue"&gt;Dim &lt;/SPAN&gt;query = &lt;SPAN style="COLOR: blue"&gt;From &lt;/SPAN&gt;c &lt;SPAN style="COLOR: blue"&gt;In &lt;/SPAN&gt;db.Customers.Include(&lt;SPAN style="COLOR: #a31515"&gt;"Orders"&lt;/SPAN&gt;) _
                &lt;SPAN style="COLOR: blue"&gt;Where &lt;/SPAN&gt;c.CustomerID = 1 _
                &lt;SPAN style="COLOR: blue"&gt;Select &lt;/SPAN&gt;c

    &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.CustomerData = &lt;SPAN style="COLOR: blue"&gt;New &lt;/SPAN&gt;CustomerCollection(query, db)

    &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.MasterViewSource = &lt;SPAN style="COLOR: blue"&gt;CType&lt;/SPAN&gt;(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.FindResource(&lt;SPAN style="COLOR: #a31515"&gt;"MasterViewSource"&lt;/SPAN&gt;), CollectionViewSource)
    &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.DetailViewSource = &lt;SPAN style="COLOR: blue"&gt;CType&lt;/SPAN&gt;(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.FindResource(&lt;SPAN style="COLOR: #a31515"&gt;"DetailsViewSource"&lt;/SPAN&gt;), CollectionViewSource)
    &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.MasterViewSource.Source = &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.CustomerData

    &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.MasterView = &lt;SPAN style="COLOR: blue"&gt;CType&lt;/SPAN&gt;(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.MasterViewSource.View, ListCollectionView)
    &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.DetailsView = &lt;SPAN style="COLOR: blue"&gt;CType&lt;/SPAN&gt;(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.DetailViewSource.View, BindingListCollectionView)
&lt;SPAN style="COLOR: blue"&gt;End Sub&lt;/SPAN&gt;&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;Private Sub &lt;/SPAN&gt;MasterView_CurrentChanged() &lt;SPAN style="COLOR: blue"&gt;Handles &lt;/SPAN&gt;MasterView.CurrentChanged
    &lt;SPAN style="COLOR: green"&gt;'We need to grab the new child view when the master's position changes
    &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.DetailsView = &lt;SPAN style="COLOR: blue"&gt;CType&lt;/SPAN&gt;(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.DetailViewSource.View, BindingListCollectionView)
&lt;SPAN style="COLOR: blue"&gt;End Sub

Private Sub &lt;/SPAN&gt;btnSave_Click() &lt;SPAN style="COLOR: blue"&gt;Handles &lt;/SPAN&gt;btnSave.Click
    &lt;SPAN style="COLOR: blue"&gt;Try
        &lt;/SPAN&gt;db.SaveChanges()
        MessageBox.Show(&lt;SPAN style="COLOR: #a31515"&gt;"Customer data saved."&lt;/SPAN&gt;, &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.Title, MessageBoxButton.OK, MessageBoxImage.Information)
    &lt;SPAN style="COLOR: blue"&gt;Catch &lt;/SPAN&gt;ex &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;Exception
        MsgBox(ex.ToString())
    &lt;SPAN style="COLOR: blue"&gt;End Try
End Sub

Private Sub &lt;/SPAN&gt;btnDelete_Click() &lt;SPAN style="COLOR: blue"&gt;Handles &lt;/SPAN&gt;btnDelete.Click
    &lt;SPAN style="COLOR: blue"&gt;If Me&lt;/SPAN&gt;.MasterView.CurrentPosition &amp;gt; -1 &lt;SPAN style="COLOR: blue"&gt;Then
        Me&lt;/SPAN&gt;.MasterView.RemoveAt(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.MasterView.CurrentPosition)
    &lt;SPAN style="COLOR: blue"&gt;End If
End Sub

Private Sub &lt;/SPAN&gt;btnAdd_Click() &lt;SPAN style="COLOR: blue"&gt;Handles &lt;/SPAN&gt;btnAdd.Click
    &lt;SPAN style="COLOR: blue"&gt;Dim &lt;/SPAN&gt;customer = &lt;SPAN style="COLOR: blue"&gt;CType&lt;/SPAN&gt;(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.MasterView.AddNew, Customer)
    &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.MasterView.CommitNew()
&lt;SPAN style="COLOR: blue"&gt;End Sub

Private Sub &lt;/SPAN&gt;btnPrevious_Click() &lt;SPAN style="COLOR: blue"&gt;Handles &lt;/SPAN&gt;btnPrevious.Click
    &lt;SPAN style="COLOR: blue"&gt;If Me&lt;/SPAN&gt;.MasterView.CurrentPosition &amp;gt; 0 &lt;SPAN style="COLOR: blue"&gt;Then
        Me&lt;/SPAN&gt;.MasterView.MoveCurrentToPrevious()
    &lt;SPAN style="COLOR: blue"&gt;End If
End Sub

Private Sub &lt;/SPAN&gt;btnNext_Click() &lt;SPAN style="COLOR: blue"&gt;Handles &lt;/SPAN&gt;btnNext.Click
    &lt;SPAN style="COLOR: blue"&gt;If Me&lt;/SPAN&gt;.MasterView.CurrentPosition &amp;lt; &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.MasterView.Count - 1 &lt;SPAN style="COLOR: blue"&gt;Then
        Me&lt;/SPAN&gt;.MasterView.MoveCurrentToNext()
    &lt;SPAN style="COLOR: blue"&gt;End If
End Sub

Private Sub &lt;/SPAN&gt;btnAddDetail_Click() &lt;SPAN style="COLOR: blue"&gt;Handles &lt;/SPAN&gt;btnAddDetail.Click
    &lt;SPAN style="COLOR: blue"&gt;Dim &lt;/SPAN&gt;order = &lt;SPAN style="COLOR: blue"&gt;CType&lt;/SPAN&gt;(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.DetailsView.AddNew, Order)
    &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.DetailsView.CommitNew()
&lt;SPAN style="COLOR: blue"&gt;End Sub

Private Sub &lt;/SPAN&gt;btnDeleteDetail_Click() &lt;SPAN style="COLOR: blue"&gt;Handles &lt;/SPAN&gt;btnDeleteDetail.Click
    &lt;SPAN style="COLOR: blue"&gt;If Me&lt;/SPAN&gt;.DetailsView.CurrentPosition &amp;gt; -1 &lt;SPAN style="COLOR: blue"&gt;Then
        Me&lt;/SPAN&gt;.DetailsView.RemoveAt(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.DetailsView.CurrentPosition)
    &lt;SPAN style="COLOR: blue"&gt;End If
End Sub&lt;/SPAN&gt;&lt;/PRE&gt;
&lt;P&gt;Now we can Add, Edit, and Delete Customer and their Orders at the same time and changes will be propagated properly to the database through Entity Framework in one call to SaveChanges. I’ve updated &lt;A href="http://code.msdn.microsoft.com/Project/Download/FileDownload.aspx?ProjectName=wpfdatavideos&amp;amp;DownloadId=6509" target=_blank mce_href="http://code.msdn.microsoft.com/Project/Download/FileDownload.aspx?ProjectName=wpfdatavideos&amp;amp;DownloadId=6509"&gt;this complete &lt;STRONG&gt;sample application&lt;/STRONG&gt;&lt;/A&gt; that demonstrates this as well as other aspects of WPF Data Binding with Entity Framework so have a look.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;UPDATE&lt;/STRONG&gt;: Milind talks about some of the tooling improvements in Visual Studio 2010 on the VSData blog regarding building WPF forms against Entity Data Models so check it out --&amp;gt;&amp;nbsp;&lt;A href="http://blogs.msdn.com/vsdata/archive/2009/05/20/wpf-data-binding-creating-a-master-details-form-in-visual-studio-2010.aspx"&gt;WPF Data Binding: Creating a Master-Details form in Visual Studio 2010&lt;/A&gt;&lt;/P&gt;
&lt;P&gt;Enjoy!&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9833642" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Visual+Basic/default.aspx">Visual Basic</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/WPF/default.aspx">WPF</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/DevCenter/default.aspx">DevCenter</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Article/default.aspx">Article</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Data/default.aspx">Data</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Entity+Framework/default.aspx">Entity Framework</category></item><item><title>WPF Data Binding Samples on Code Gallery</title><link>http://blogs.msdn.com/bethmassi/archive/2009/06/17/wpf-data-binding-samples-on-code-gallery.aspx</link><pubDate>Wed, 17 Jun 2009 22:41:28 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9770286</guid><dc:creator>Beth Massi</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/bethmassi/comments/9770286.aspx</comments><wfw:commentRss>http://blogs.msdn.com/bethmassi/commentrss.aspx?PostID=9770286</wfw:commentRss><wfw:comment>http://blogs.msdn.com/bethmassi/rsscomments.aspx?PostID=9770286</wfw:comment><description>&lt;p&gt;One of the many &lt;a href="http://msdn.microsoft.com/en-us/vstudio/dd238515.aspx" target="_blank"&gt;samples released for Visual Studio 2010 Beta 1&lt;/a&gt; that you should be aware of are examples of WPF data binding against Entity Data Models. You can find some easy to follow samples here: &lt;a href="http://code.msdn.microsoft.com/WPFDatabinding"&gt;&lt;strong&gt;http://code.msdn.microsoft.com/WPFDatabinding&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;This sample demonstrates how to create a WPF Forms solution that checks user input with validation code, demonstrates common controls such as DataGrid and ComboBox, and shows typical data manipulation including create, read, update, and delete. The sample solution is available in both Visual Basic and C# and is intended for use with Visual Studio 2010 Beta 1 and with the .NET Framework 3.5.&amp;#160; In the future, we will release a sample that performs with the .Net Framework 4.0 Beta.&lt;/p&gt;  &lt;p&gt;Check out the &lt;a href="http://blogs.msdn.com/vsdata" target="_blank"&gt;VS Data Team blog&lt;/a&gt; for more information on WPF data-binding and Karl’s blog on a great &lt;a href="http://karlshifflett.wordpress.com/2009/06/10/wpf-sample-series-listbox-grouping-sorting-subtotals-and-collapsible-regions/" target="_blank"&gt;WPF sample series&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Enjoy!&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9770286" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/bethmassi/archive/tags/WPF/default.aspx">WPF</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/DevCenter/default.aspx">DevCenter</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Data/default.aspx">Data</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Entity+Framework/default.aspx">Entity Framework</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/VS2010/default.aspx">VS2010</category></item><item><title>Visual Studio 2010 Beta 1 – Everyone can download and play today!</title><link>http://blogs.msdn.com/bethmassi/archive/2009/05/20/visual-studio-2010-beta-1-everyone-can-download-and-play-today.aspx</link><pubDate>Wed, 20 May 2009 20:50:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9632575</guid><dc:creator>Beth Massi</dc:creator><slash:comments>11</slash:comments><comments>http://blogs.msdn.com/bethmassi/comments/9632575.aspx</comments><wfw:commentRss>http://blogs.msdn.com/bethmassi/commentrss.aspx?PostID=9632575</wfw:commentRss><wfw:comment>http://blogs.msdn.com/bethmassi/rsscomments.aspx?PostID=9632575</wfw:comment><description>&lt;P&gt;Here it is folks, Visual Studio 2010 Beta 1 has been released to the public today. Check out the &lt;A href="http://go.microsoft.com/fwlink/?LinkID=151797" mce_href="http://go.microsoft.com/fwlink/?LinkID=151797"&gt;&lt;STRONG&gt;Visual Studio 2010 and .NET Framework 4 Beta 1 site&lt;/STRONG&gt;&lt;/A&gt; to download the Beta, submit product feedback on the &lt;A href="http://social.msdn.microsoft.com/Forums/en-US/category/VSPreRelease,netdevelopmentprerelease,visualstudioprerelease,vstsprerelease" target=_blank mce_href="http://social.msdn.microsoft.com/Forums/en-US/category/VSPreRelease,netdevelopmentprerelease,visualstudioprerelease,vstsprerelease"&gt;Beta 1 Forums&lt;/A&gt;, report bugs on &lt;A href="http://go.microsoft.com/fwlink/?LinkID=151484" target=_blank mce_href="http://go.microsoft.com/fwlink/?LinkID=151484"&gt;Connect&lt;/A&gt;, and find additional information. Also visit the &lt;A href="http://msdn.microsoft.com/en-us/vstudio/dd441784.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/vstudio/dd441784.aspx"&gt;Beta 1 walkthroughs page&lt;/A&gt; for information on how to use the new features and download the &lt;A href="http://msdn.microsoft.com/en-us/vstudio/dd238515.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/vstudio/dd238515.aspx"&gt;Visual Studio 2010 Samples&lt;/A&gt;. There’s also some good language-focused resources on the &lt;A href="http://msdn.microsoft.com/en-us/vbasic/dd819153.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/vbasic/dd819153.aspx"&gt;Visual Basic 2010&lt;/A&gt; and &lt;A href="http://msdn.microsoft.com/en-us/vcsharp/dd819407.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/vcsharp/dd819407.aspx"&gt;C# 2010&lt;/A&gt; that are hanging off the Developer Centers. &lt;/P&gt;
&lt;P&gt;Some of my favorite features include those around the &lt;A href="http://windowsclient.net/wpfdesigner" target=_blank mce_href="http://windowsclient.net/wpfdesigner"&gt;WPF Designer&lt;/A&gt; and the Data Sources Window which now supports the same drag-drop RAD experience of Winforms in WPF applications:&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;A href="http://msdn.microsoft.com/en-us/library/dd465159(VS.100).aspx" mce_href="http://msdn.microsoft.com/en-us/library/dd465159(VS.100).aspx"&gt;Walkthrough: Binding WPF Controls to an Entity Data Model&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://msdn.microsoft.com/en-us/library/dd547149(VS.100).aspx" mce_href="http://msdn.microsoft.com/en-us/library/dd547149(VS.100).aspx"&gt;Walkthrough: Binding WPF Controls to a Dataset&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://msdn.microsoft.com/en-us/library/dd465161(VS.100).aspx" mce_href="http://msdn.microsoft.com/en-us/library/dd465161(VS.100).aspx"&gt;Walkthrough: Binding WPF Controls to an ADO.NET Data Service&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://msdn.microsoft.com/en-us/library/dd465158(VS.100).aspx" mce_href="http://msdn.microsoft.com/en-us/library/dd465158(VS.100).aspx"&gt;Walkthrough: Displaying Related Data in a WPF Application&lt;/A&gt;&lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;For Office solutions, check out the &lt;A href="http://msdn.microsoft.com/en-us/library/dd234217(VS.100).aspx" mce_href="http://msdn.microsoft.com/en-us/library/dd234217(VS.100).aspx"&gt;Advanced Office Solution Deployment&lt;/A&gt; topic in the library and the &lt;A href="http://blogs.msdn.com/vsto/" target=_blank mce_href="http://blogs.msdn.com/vsto/"&gt;VSTO Team blog&lt;/A&gt; for some cool new Office client features:&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;A href="http://msdn.microsoft.com/en-us/library/dd465290(VS.100).aspx" mce_href="http://msdn.microsoft.com/en-us/library/dd465290(VS.100).aspx"&gt;Walkthrough: Deploying Multiple Office Solutions in a Single ClickOnce Installer&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://msdn.microsoft.com/en-us/library/dd465291(VS.100).aspx" mce_href="http://msdn.microsoft.com/en-us/library/dd465291(VS.100).aspx"&gt;Walkthrough: Copying a Document to the End User Computer after a ClickOnce Installation&lt;/A&gt;&lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;Take a look through the &lt;A href="http://msdn.microsoft.com/en-us/library/dd547188(VS.100).aspx" mce_href="http://msdn.microsoft.com/en-us/library/dd547188(VS.100).aspx"&gt;Visual Studio 2010 Product Highlights&lt;/A&gt; and &lt;A href="http://msdn.microsoft.com/en-us/library/bb386063(VS.100).aspx" mce_href="http://msdn.microsoft.com/en-us/library/bb386063(VS.100).aspx"&gt;What's New in Visual Studio 2010&lt;/A&gt; for more info on other new features including &lt;A href="http://msdn.microsoft.com/en-us/library/z4y0hsax(VS.100).aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/library/z4y0hsax(VS.100).aspx"&gt;multi-monitor&lt;/A&gt; – YUMMY! :-)&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;New Team Bloggers&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;I’d also like to introduce the “come-back” of the &lt;A href="http://blogs.msdn.com/vsdata/" target=_blank mce_href="http://blogs.msdn.com/vsdata/"&gt;Visual Studio Data team blog&lt;/A&gt;. We’ve got a lot of new faces on the team that are building some amazing tools in Visual Studio to help you build business applications. They’ll be posting a lot of great &lt;A href="http://blogs.msdn.com/vsdata/archive/tags/VS2010/default.aspx" target=_blank mce_href="http://blogs.msdn.com/vsdata/archive/tags/VS2010/default.aspx"&gt;VS 2010 content here&lt;/A&gt;.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Visual Studio 2010 Beta 1 resources:&lt;/STRONG&gt;&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;A href="http://go.microsoft.com/fwlink/?LinkID=151797" mce_href="http://go.microsoft.com/fwlink/?LinkID=151797"&gt;&lt;STRONG&gt;Visual Studio 2010 and .NET Framework 4 Beta 1 site&lt;/STRONG&gt;&lt;/A&gt; &lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://go.microsoft.com/?linkid=9665216" mce_href="http://go.microsoft.com/?linkid=9665216"&gt;Visual Studio 2010 and .NET Framework 4.0 Training Kit &lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://msdn.microsoft.com/en-us/vstudio/dd238515.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/vstudio/dd238515.aspx"&gt;Visual Studio 2010 Samples&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://msdn.microsoft.com/en-us/vstudio/dd441784.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/vstudio/dd441784.aspx"&gt;Visual Studio 2010 Beta 1 Walkthroughs&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://windowsclient.net/wpfdesigner" mce_href="http://windowsclient.net/wpfdesigner"&gt;WPF and Silverlight Designer Walkthroughs&lt;/A&gt;&amp;nbsp;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://msdn.microsoft.com/en-us/library/bb386063(VS.100).aspx" mce_href="http://msdn.microsoft.com/en-us/library/bb386063(VS.100).aspx"&gt;What's New in Visual Studio 2010&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://msdn.microsoft.com/en-us/library/dd547188(VS.100).aspx" mce_href="http://msdn.microsoft.com/en-us/library/dd547188(VS.100).aspx"&gt;Visual Studio 2010 Product Highlights&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://msdn.microsoft.com/en-us/vbasic/dd819153.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/vbasic/dd819153.aspx"&gt;Visual Basic 2010&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://msdn.microsoft.com/en-us/vcsharp/dd819407.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/vcsharp/dd819407.aspx"&gt;C# 2010&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://msdn.microsoft.com/en-us/library/dd831853(VS.100).aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/library/dd831853(VS.100).aspx"&gt;VS 2010 Library&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://channel9.msdn.com/tags/Visual%20Studio%202010/"&gt;Visual Studio 2010 on Channel 9&lt;/A&gt;&lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;&lt;STRONG&gt;My recommended blogs on VS 2010:&lt;/STRONG&gt;&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;A href="http://blogs.msdn.com/vsdata/archive/tags/VS2010/default.aspx" target=_blank mce_href="http://blogs.msdn.com/vsdata/archive/tags/VS2010/default.aspx"&gt;Visual Studio Data Team&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://blogs.msdn.com/vsto/archive/tags/VS2010/default.aspx" target=_blank mce_href="http://blogs.msdn.com/vsto/archive/tags/VS2010/default.aspx"&gt;VSTO Team&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://blogs.msdn.com/vbteam/archive/tags/VB2010/default.aspx" target=_blank mce_href="http://blogs.msdn.com/vbteam/archive/tags/VB2010/default.aspx"&gt;Visual Basic Team&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="http://blogs.msdn.com/jasonz/" target=_blank mce_href="http://blogs.msdn.com/jasonz/"&gt;Jason Zander&lt;/A&gt; (executive blog) &lt;/LI&gt;
&lt;LI&gt;and &lt;A href="http://blogs.msdn.com/bethmassi/archive/tags/VS2010/default.aspx" target=_blank mce_href="http://blogs.msdn.com/bethmassi/archive/tags/VS2010/default.aspx"&gt;Me&lt;/A&gt; ;-)&lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;Enjoy!&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9632575" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/bethmassi/archive/tags/WPF/default.aspx">WPF</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/DevCenter/default.aspx">DevCenter</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Data/default.aspx">Data</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/VS2010/default.aspx">VS2010</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/VSTO/default.aspx">VSTO</category></item><item><title>Using TableAdapters to Insert Related Data into an MS Access Database</title><link>http://blogs.msdn.com/bethmassi/archive/2009/05/14/using-tableadapters-to-insert-related-data-into-an-ms-access-database.aspx</link><pubDate>Fri, 15 May 2009 03:48:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9617454</guid><dc:creator>Beth Massi</dc:creator><slash:comments>43</slash:comments><comments>http://blogs.msdn.com/bethmassi/comments/9617454.aspx</comments><wfw:commentRss>http://blogs.msdn.com/bethmassi/commentrss.aspx?PostID=9617454</wfw:commentRss><wfw:comment>http://blogs.msdn.com/bethmassi/rsscomments.aspx?PostID=9617454</wfw:comment><description>&lt;P&gt;I’ve &lt;A href="http://blogs.msdn.com/bethmassi/archive/2007/07/10/working-with-tableadapters-related-datatables-and-transactions.aspx" target=_blank mce_href="http://blogs.msdn.com/bethmassi/archive/2007/07/10/working-with-tableadapters-related-datatables-and-transactions.aspx"&gt;posted before&lt;/A&gt; about how to use TableAdapters to update parent-child (master-detail) relationships against SQL server. It’s pretty straightforward and Visual Studio generates all the code for you to properly insert, update and delete your data. However if you’re using MS Access then there’s one thing that Visual Studio doesn’t do because it’s not supported when using Access.&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;How Parent-Child Inserts Work&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;When Visual Studio generates the insert commands on a SQL-Server TableAdapter it looks to see if the table’s primary keys are auto-generated (identity columns) and if so, Visual Studio will write an additional statement to retrieve the key using the &lt;A href="http://msdn.microsoft.com/en-us/library/ms190315.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/library/ms190315.aspx"&gt;SCOPE_IDENTITY&lt;/A&gt; functionality of SQL Server. When in the DataSet designer, if you look at the insert statement in the properties window for the SQLTableAdapter you will see &lt;STRONG&gt;two &lt;/STRONG&gt;statements separated by a semi-colon:&lt;/P&gt;
&lt;P&gt;&lt;A href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/UsingTableAdapterstoInsertRelatedDataint_D5FF/image_2.png" mce_href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/UsingTableAdapterstoInsertRelatedDataint_D5FF/image_2.png"&gt;&lt;IMG title=image style="BORDER-TOP-WIDTH: 0px; DISPLAY: inline; BORDER-LEFT-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 0px; BORDER-RIGHT-WIDTH: 0px" height=352 alt=image src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/UsingTableAdapterstoInsertRelatedDataint_D5FF/image_thumb.png" width=571 border=0 mce_src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/UsingTableAdapterstoInsertRelatedDataint_D5FF/image_thumb.png"&gt;&lt;/A&gt; &lt;/P&gt;
&lt;P&gt;&lt;FONT face="Courier New" size=2&gt;INSERT INTO [dbo].[Products] ([ProductName], [SupplierID], [CategoryID], [QuantityPerUnit], [UnitPrice], [UnitsInStock], [UnitsOnOrder], [ReorderLevel], [Discontinued]) VALUES (@ProductName, @SupplierID, @CategoryID, @QuantityPerUnit, @UnitPrice, @UnitsInStock, @UnitsOnOrder, @ReorderLevel, @Discontinued&lt;/FONT&gt;&lt;STRONG&gt;&lt;FONT face="Courier New" size=2&gt;); &lt;BR&gt;SELECT ProductID, ProductName, SupplierID, CategoryID, QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder, ReorderLevel, Discontinued FROM Products WHERE (ProductID = SCOPE_IDENTITY())&lt;/FONT&gt;&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;SQL Server supports batch statements through ADO.NET commands so this will populate the primary key back in the DataRow inside the DataSet as each row is inserted into the database. If you are enforcing foreign key constraints with a parent-child relation set up on two DataTables and you set the Update Rule to Cascade then any foreign key references will also be updated in the children. Because the TableAdapterManager will save the children after their parent records, when the child saves to the database it will contain the correct parent key which must already exist in the database before a child can be inserted in order to maintain referential integrity in the database. &lt;/P&gt;
&lt;P&gt;Unfortunately Access doesn’t support batch statements. If you look at what is generated for Access you will only see one statement (also the OLEDB provider does not support named parameters hence the question mark placeholders):&lt;/P&gt;
&lt;P&gt;&lt;FONT face="Courier New" size=2&gt;INSERT INTO `Products` (`ProductName`, `SupplierID`, `CategoryID`, `QuantityPerUnit`, `UnitPrice`, `UnitsInStock`, `UnitsOnOrder`, `ReorderLevel`, `Discontinued`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)&lt;/FONT&gt;&lt;/P&gt;
&lt;P&gt;So if you are doing inserts, especially for related parent-child data, you need a way to intercept the DataRow and set the primary key right &lt;STRONG&gt;after &lt;/STRONG&gt;the row is inserted into the database and &lt;STRONG&gt;before &lt;/STRONG&gt;any children are inserted. There’s an &lt;A href="http://msdn.microsoft.com/en-us/library/ms971502.aspx#manidcrisis_topic2" target=_blank mce_href="http://msdn.microsoft.com/en-us/library/ms971502.aspx#manidcrisis_topic2"&gt;excellent article by Bill Vaughn (VB MVP) that explains this issue&lt;/A&gt; as well as &lt;A href="http://support.microsoft.com/kb/815629" target=_blank mce_href="http://support.microsoft.com/kb/815629"&gt;a KB Article&lt;/A&gt; that shows how to solve it using the DataAdapter. These were written before Visual Studio had the concept of TableAdapters (which were added in VS 2008) so let’s see how we could use this technique to enhance our TableAdapters via partial classes.&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Setting up the Parent-Child DataSet&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;The first step is to make sure you set up the tables in your Access database to use the AutoNumber feature for the primary keys on the rows. Here I’m using Access 2007 against the Northwind Access database. AutoNumber is used for both the primary keys on the Products and Categories tables:&lt;/P&gt;
&lt;P&gt;&lt;A href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/UsingTableAdapterstoInsertRelatedDataint_D5FF/image_4.png" mce_href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/UsingTableAdapterstoInsertRelatedDataint_D5FF/image_4.png"&gt;&lt;IMG title=image style="BORDER-RIGHT: 0px; BORDER-TOP: 0px; DISPLAY: inline; BORDER-LEFT: 0px; BORDER-BOTTOM: 0px" height=398 alt=image src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/UsingTableAdapterstoInsertRelatedDataint_D5FF/image_thumb_1.png" width=508 border=0 mce_src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/UsingTableAdapterstoInsertRelatedDataint_D5FF/image_thumb_1.png"&gt;&lt;/A&gt; &lt;/P&gt;
&lt;P&gt;Next you need to make sure you set up the relationship on the DataSet properly so that the primary key on the parent will cascade to the foreign key on the child. Set the relation in the DataSet designer to "Both Relation and Foreign Key Constraint" and then set the Update and Delete rules to Cascade. Just right-click on the relation and select "Edit Relation" in the DataSet designer:&lt;/P&gt;
&lt;P&gt;&lt;A href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/UsingTableAdapterstoInsertRelatedDataint_D5FF/image_6.png" mce_href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/UsingTableAdapterstoInsertRelatedDataint_D5FF/image_6.png"&gt;&lt;IMG title=image style="BORDER-RIGHT: 0px; BORDER-TOP: 0px; DISPLAY: inline; BORDER-LEFT: 0px; BORDER-BOTTOM: 0px" height=244 alt=image src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/UsingTableAdapterstoInsertRelatedDataint_D5FF/image_thumb_2.png" width=410 border=0 mce_src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/UsingTableAdapterstoInsertRelatedDataint_D5FF/image_thumb_2.png"&gt;&lt;/A&gt;&amp;nbsp;&lt;A href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/UsingTableAdapterstoInsertRelatedDataint_D5FF/image_8.png" mce_href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/UsingTableAdapterstoInsertRelatedDataint_D5FF/image_8.png"&gt;&lt;IMG title=image style="BORDER-RIGHT: 0px; BORDER-TOP: 0px; DISPLAY: inline; BORDER-LEFT: 0px; BORDER-BOTTOM: 0px" height=491 alt=image src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/UsingTableAdapterstoInsertRelatedDataint_D5FF/image_thumb_3.png" width=512 border=0 mce_src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/UsingTableAdapterstoInsertRelatedDataint_D5FF/image_thumb_3.png"&gt;&lt;/A&gt; &lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Loading and Editing the Parent-Child DataSet&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;You now are telling the DataSet to enforce the foreign key relationship which means that you &lt;STRONG&gt;must&lt;/STRONG&gt; have a parent for every child. This means you have to load the data in parent then child order. You also have to be careful with your queries. You have to &lt;STRONG&gt;make sure that every row in the child DataTable will have a corresponding parent row in the parent DataTable&lt;/STRONG&gt;. This also means that you have to make sure to call EndEdit on any new parent BindingSource before any children can be added. &lt;/P&gt;
&lt;P&gt;For example, from the Data Sources window drag the Categories parent table as details and the related child Products table as a DataGridView on the form and Visual Studio will generate the code to load and save our data. &lt;/P&gt;
&lt;P&gt;&lt;A href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/UsingTableAdapterstoInsertRelatedDataint_D5FF/image_10.png" mce_href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/UsingTableAdapterstoInsertRelatedDataint_D5FF/image_10.png"&gt;&lt;IMG title=image style="BORDER-RIGHT: 0px; BORDER-TOP: 0px; DISPLAY: inline; BORDER-LEFT: 0px; BORDER-BOTTOM: 0px" height=443 alt=image src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/UsingTableAdapterstoInsertRelatedDataint_D5FF/image_thumb_4.png" width=677 border=0 mce_src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/UsingTableAdapterstoInsertRelatedDataint_D5FF/image_thumb_4.png"&gt;&lt;/A&gt; &lt;/P&gt;
&lt;P&gt;Head over to the code behind and make sure that the parent is filled first before the child. Also make sure that EndEdit is called on the CategoriesBindingSource &lt;STRONG&gt;before &lt;/STRONG&gt;a new product can be inserted into the DataGridView. EndEdit will flush the data row being edited by the controls into the DataTable. In this example I just am calling EndEdit on the CategoriesBindingSource when the user selects the grid. &lt;/P&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;Public Class &lt;/SPAN&gt;Form1

    &lt;SPAN style="COLOR: blue"&gt;Private Sub &lt;/SPAN&gt;CategoriesBindingNavigatorSaveItem_Click() _
            &lt;SPAN style="COLOR: blue"&gt;Handles &lt;/SPAN&gt;CategoriesBindingNavigatorSaveItem.Click
        &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.Validate()
        &lt;SPAN style="COLOR: green"&gt;'Call EndEdit on all BindingSources! 
        &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.CategoriesBindingSource.EndEdit()
        &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.ProductsBindingSource.EndEdit()
        &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.TableAdapterManager.UpdateAll(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.ProductsDataSet)
    &lt;SPAN style="COLOR: blue"&gt;End Sub

    Private Sub &lt;/SPAN&gt;Form1_Load() &lt;SPAN style="COLOR: blue"&gt;Handles MyBase&lt;/SPAN&gt;.Load
        &lt;SPAN style="COLOR: green"&gt;'Load parent before child!
        &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.CategoriesTableAdapter.Fill(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.ProductsDataSet.Categories)
        &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.ProductsTableAdapter.Fill(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.ProductsDataSet.Products)
    &lt;SPAN style="COLOR: blue"&gt;End Sub

    Private Sub &lt;/SPAN&gt;ProductsDataGridView_Enter() &lt;SPAN style="COLOR: blue"&gt;Handles &lt;/SPAN&gt;ProductsDataGridView.Enter
        &lt;SPAN style="COLOR: green"&gt;'You must commit the parent row to the DataTable before adding child rows 
        &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.CategoriesBindingSource.EndEdit()
    &lt;SPAN style="COLOR: blue"&gt;End Sub

End Class&lt;/SPAN&gt;&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;Note that anytime you call EndEdit and flush the data to the DataTable, the row must not fail any constraints either (i.e. if NULLs aren’t being allowed then you have to set those values). One way to handle this is to add code to set default values in the &lt;A href="http://msdn.microsoft.com/en-us/library/system.data.datatable.tablenewrow.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/library/system.data.datatable.tablenewrow.aspx"&gt;TableNewRow&lt;/A&gt; handler on the DataTable. &lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Enhancing the TableAdapter Partial Classes&lt;/STRONG&gt;&lt;/P&gt;
&lt;P mce_keep="true"&gt;&amp;nbsp;&lt;/P&gt;
&lt;P mce_keep="true"&gt;&amp;nbsp;&lt;/P&gt;
&lt;P mce_keep="true"&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Now for the good stuff. Like I mentioned in the beginning, you need a way to set the primary key on the parent right after the row is inserted into the database and before any children are inserted. Now that we have keys cascading we just need to write code to handle the RowUpdated event on the DataAdapter inside the TableAdapter partial class. TableAdapters are generated classes that Visual Studio creates for us from the DataSet designer. These classes are declared as &lt;A href="http://msdn.microsoft.com/en-us/library/yfzd5350.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/library/yfzd5350.aspx"&gt;Partial Classes&lt;/A&gt; so that means we can add code to the same class even if it’s in a separate file. Right-click on the TableAdapter class in the DataSet Designer and select View Code and the partial class file that you can edit will be created for you. &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;Namespace &lt;/SPAN&gt;ProductsDataSetTableAdapters

    &lt;SPAN style="COLOR: blue"&gt;Partial Public Class &lt;/SPAN&gt;CategoriesTableAdapter

    &lt;SPAN style="COLOR: blue"&gt;End Class

    Partial Public Class &lt;/SPAN&gt;ProductsTableAdapter

    &lt;SPAN style="COLOR: blue"&gt;End Class
End Namespace&lt;/SPAN&gt;&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;In these classes we can handle the RowUpdated event on the private variable _adapter which gives us access to the ADO.NET DataAdapter that is executing the updates to our rows. The way we retrieve the primary key is by executing the statement&amp;nbsp; SELECT @@IDENTITY which tells Access to send back the last primary key it used on the connection. Because you have to add this handler to all your TableAdapters that are working against MS Access, to make things more manageable you can create a class with a Shared (static) method to handle setting the key and then call that from the handlers.&lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;Imports &lt;/SPAN&gt;System.Data.OleDb

&lt;SPAN style="COLOR: blue"&gt;Public Class &lt;/SPAN&gt;AccessIDHelper
    &lt;SPAN style="COLOR: green"&gt;''' &amp;lt;summary&amp;gt;
    ''' Retrieves the primary key autonumber values from Access
    ''' &amp;lt;/summary&amp;gt;
    ''' &amp;lt;remarks&amp;gt;&amp;lt;/remarks&amp;gt;
    &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Public Shared Sub &lt;/SPAN&gt;SetPrimaryKey(&lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;trans &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;OleDbTransaction, _
                                    &lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;e &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;OleDbRowUpdatedEventArgs)
        &lt;SPAN style="COLOR: blue"&gt;If &lt;/SPAN&gt;e.Status = UpdateStatus.Continue &lt;SPAN style="COLOR: blue"&gt;AndAlso &lt;/SPAN&gt;_
           e.StatementType = StatementType.Insert &lt;SPAN style="COLOR: blue"&gt;Then
            &lt;/SPAN&gt;&lt;SPAN style="COLOR: green"&gt;' If this is an INSERT operation...
            &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Dim &lt;/SPAN&gt;pk = e.Row.Table.PrimaryKey
            &lt;SPAN style="COLOR: green"&gt;' and a primary key column exists...
            &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;If &lt;/SPAN&gt;pk &lt;SPAN style="COLOR: blue"&gt;IsNot Nothing AndAlso &lt;/SPAN&gt;pk.Count = 1 &lt;SPAN style="COLOR: blue"&gt;Then
                Dim &lt;/SPAN&gt;cmdGetIdentity &lt;SPAN style="COLOR: blue"&gt;As New &lt;/SPAN&gt;OleDbCommand(&lt;SPAN style="COLOR: #a31515"&gt;"SELECT @@IDENTITY"&lt;/SPAN&gt;, trans.Connection, trans)
                &lt;SPAN style="COLOR: green"&gt;' Execute the post-update query to fetch new @@Identity
                &lt;/SPAN&gt;e.Row(pk(0)) = &lt;SPAN style="COLOR: blue"&gt;CInt&lt;/SPAN&gt;(cmdGetIdentity.ExecuteScalar)
                e.Row.AcceptChanges()
            &lt;SPAN style="COLOR: blue"&gt;End If
        End If
    End Sub
End Class

Namespace &lt;/SPAN&gt;ProductsDataSetTableAdapters

    &lt;SPAN style="COLOR: blue"&gt;Partial Public Class &lt;/SPAN&gt;CategoriesTableAdapter

        &lt;SPAN style="COLOR: blue"&gt;Private Sub &lt;/SPAN&gt;_adapter_RowUpdated(&lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;sender &lt;SPAN style="COLOR: blue"&gt;As Object&lt;/SPAN&gt;, _
                                        &lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;e &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;System.Data.OleDb.OleDbRowUpdatedEventArgs) _
                                        &lt;SPAN style="COLOR: blue"&gt;Handles &lt;/SPAN&gt;_adapter.RowUpdated

            AccessIDHelper.SetPrimaryKey(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.Transaction, e)
        &lt;SPAN style="COLOR: blue"&gt;End Sub
    End Class

    Partial Public Class &lt;/SPAN&gt;ProductsTableAdapter

        &lt;SPAN style="COLOR: blue"&gt;Private Sub &lt;/SPAN&gt;_adapter_RowUpdated(&lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;sender &lt;SPAN style="COLOR: blue"&gt;As Object&lt;/SPAN&gt;, _
                                        &lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;e &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;System.Data.OleDb.OleDbRowUpdatedEventArgs) _
                                        &lt;SPAN style="COLOR: blue"&gt;Handles &lt;/SPAN&gt;_adapter.RowUpdated

            AccessIDHelper.SetPrimaryKey(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.Transaction, e)
        &lt;SPAN style="COLOR: blue"&gt;End Sub
    End Class
End Namespace&lt;/SPAN&gt;&lt;/PRE&gt;
&lt;P&gt;So that’s how you can get the primary keys into the data rows and have them properly cascaded to the child rows. So now when the children are updated they will have the correct foreign key and the parent will exist in the database. I hope this helps clear up how to work with Access and Visual Studio.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;I’ve &lt;A href="http://code.msdn.microsoft.com/AccessDataVS/" target=_blank mce_href="http://code.msdn.microsoft.com/AccessDataVS/"&gt;posted this example on CodeGallery&lt;/A&gt; so have a look.&lt;/P&gt;
&lt;P&gt;Enjoy!&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9617454" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Visual+Basic/default.aspx">Visual Basic</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/VS2008/default.aspx">VS2008</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Winforms/default.aspx">Winforms</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/DevCenter/default.aspx">DevCenter</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Article/default.aspx">Article</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Data/default.aspx">Data</category></item><item><title>Using the WPF ObservableCollection with EF Entities</title><link>http://blogs.msdn.com/bethmassi/archive/2009/05/08/using-the-wpf-observablecollection-with-ef-entities.aspx</link><pubDate>Sat, 09 May 2009 01:29:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9597952</guid><dc:creator>Beth Massi</dc:creator><slash:comments>12</slash:comments><comments>http://blogs.msdn.com/bethmassi/comments/9597952.aspx</comments><wfw:commentRss>http://blogs.msdn.com/bethmassi/commentrss.aspx?PostID=9597952</wfw:commentRss><wfw:comment>http://blogs.msdn.com/bethmassi/rsscomments.aspx?PostID=9597952</wfw:comment><description>&lt;P&gt;The &lt;A href="http://msdn.microsoft.com/en-us/library/ms668604.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/library/ms668604.aspx"&gt;ObservableCollection&lt;/A&gt; is a special WPF collection that provides proper notifications to the UI when items are added, removed, or the list is refreshed because it implements &lt;A href="http://msdn.microsoft.com/en-us/library/system.collections.specialized.inotifycollectionchanged.aspx" mce_href="http://msdn.microsoft.com/en-us/library/system.collections.specialized.inotifycollectionchanged.aspx"&gt;INotifyCollectionChanged&lt;/A&gt;. It’s common to use this collection (or inherit from it) to contain your business objects you want to bind to in WPF.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;Class &lt;/SPAN&gt;Window1&lt;BR&gt;&lt;SPAN style="COLOR: blue"&gt;    Private &lt;/SPAN&gt;CustomerData &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;ObservableCollection(&lt;SPAN style="COLOR: blue"&gt;Of &lt;/SPAN&gt;Customer)&lt;/PRE&gt;
&lt;P&gt;You can then set up a &lt;A href="http://msdn.microsoft.com/en-us/library/system.windows.data.collectionviewsource.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/library/system.windows.data.collectionviewsource.aspx"&gt;CollectionViewSource&lt;/A&gt; and use it’s View property to get a reference to the &lt;A href="http://msdn.microsoft.com/en-us/library/system.windows.data.listcollectionview.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/library/system.windows.data.listcollectionview.aspx"&gt;ListCollectionView&lt;/A&gt; in order to add and remove items instead of working with the source collection directly. This decouples your data source (and therefore any collection logic) from the form itself making it much easier to change sources later. I’ve showed &lt;A href="http://blogs.msdn.com/bethmassi/archive/2008/11/07/loading-data-and-binding-controls-in-wpf-with-collectionviewsource.aspx" target=_blank mce_href="http://blogs.msdn.com/bethmassi/archive/2008/11/07/loading-data-and-binding-controls-in-wpf-with-collectionviewsource.aspx"&gt;how to use CollectionViewSources before&lt;/A&gt; but basically you just declare them in the Window.Resources section and bind to them in XAML: &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;&amp;lt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;Window &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;x&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;:&lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Class&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="Window1"
    &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;xmlns&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;xmlns&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;:&lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;x&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="http://schemas.microsoft.com/winfx/2006/xaml"
    &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Title&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="Window1" &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Height&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="282" &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Width&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="440" &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Name&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="Window1"&amp;gt;
    &amp;lt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;Window.Resources&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;&amp;gt;
      &lt;STRONG&gt;  &amp;lt;&lt;/STRONG&gt;&lt;/SPAN&gt;&lt;STRONG&gt;&lt;SPAN style="COLOR: #a31515"&gt;CollectionViewSource &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;x&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;:&lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;Key&lt;/SPAN&gt;&lt;/STRONG&gt;&lt;SPAN style="COLOR: blue"&gt;&lt;STRONG&gt;="CustomerSource" /&amp;gt;&lt;/STRONG&gt;
    &amp;lt;/&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;Window.Resources&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;&amp;gt;
    &amp;lt;&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;Grid &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;DataContext&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;="{&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;Binding &lt;/SPAN&gt;&lt;STRONG&gt;&lt;SPAN style="COLOR: red"&gt;Source&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;={&lt;/SPAN&gt;&lt;SPAN style="COLOR: #a31515"&gt;StaticResource &lt;/SPAN&gt;&lt;SPAN style="COLOR: red"&gt;CustomerSource&lt;/SPAN&gt;&lt;/STRONG&gt;&lt;SPAN style="COLOR: blue"&gt;&lt;STRONG&gt;}&lt;/STRONG&gt;}"&amp;gt;&lt;/SPAN&gt;&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;And then you can set the Source property in code to your collection and obtain the ListCollectionView. &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;Dim &lt;/SPAN&gt;customerSource = &lt;SPAN style="COLOR: blue"&gt;CType&lt;/SPAN&gt;(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.Resources(&lt;SPAN style="COLOR: #a31515"&gt;"CustomerSource"&lt;/SPAN&gt;), CollectionViewSource)
customerSource.&lt;STRONG&gt;Source&lt;/STRONG&gt; = &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.CustomerData

&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.View = &lt;SPAN style="COLOR: blue"&gt;CType&lt;/SPAN&gt;(customerSource.&lt;STRONG&gt;View&lt;/STRONG&gt;, ListCollectionView)&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;Then you use the View to add and remove items from the collection and the UI will update properly: &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;Private Sub &lt;/SPAN&gt;btnDelete_Click() &lt;SPAN style="COLOR: blue"&gt;Handles &lt;/SPAN&gt;btnDelete.Click
       &lt;SPAN style="COLOR: blue"&gt;If Me&lt;/SPAN&gt;.View.CurrentPosition &amp;gt; -1 &lt;SPAN style="COLOR: blue"&gt;Then
           &lt;/SPAN&gt;&lt;SPAN style="COLOR: green"&gt;'removes the currently selected customer from the underlying collection 
           &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.View.RemoveAt(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.View.CurrentPosition)
       &lt;SPAN style="COLOR: blue"&gt;End If
   End Sub

   Private Sub &lt;/SPAN&gt;btnAdd_Click() &lt;SPAN style="COLOR: blue"&gt;Handles &lt;/SPAN&gt;btnAdd.Click
       &lt;SPAN style="COLOR: green"&gt;'adds a new customer to the underlying collection 
       &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Dim &lt;/SPAN&gt;customer = &lt;SPAN style="COLOR: blue"&gt;CType&lt;/SPAN&gt;(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.View.AddNew, Customer)
       &lt;SPAN style="COLOR: green"&gt;'do something with customer if needed...
       &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.View.CommitNew()
   &lt;SPAN style="COLOR: blue"&gt;End Sub&lt;/SPAN&gt;&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;Calling these methods on the ListCollectionView will execute the &lt;A href="http://msdn.microsoft.com/en-us/library/ms654928.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/library/ms654928.aspx"&gt;InsertItem&lt;/A&gt; and &lt;A href="http://msdn.microsoft.com/en-us/library/ms654938.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/library/ms654938.aspx"&gt;RemoveItem&lt;/A&gt; methods on the ObservableCollection.&lt;/P&gt;
&lt;P&gt;Now if you are using an &lt;A href="http://msdn.microsoft.com/en-us/library/bb387122.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/library/bb387122.aspx"&gt;Entity Data Model (EDM)&lt;/A&gt; the designer in Visual Studio 2008 SP1 will generate entity classes for you that you can also bind to in your UI. Access to these entities is done through the &lt;A href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.aspx" target=_blank mce_href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.aspx"&gt;ObjectContext&lt;/A&gt; and the designer also creates a class for you that inherits from this when you create the EDM. It is named something like xxxEntites. (For instance, in Visual Studio 2008 SP1 “Add New Item” and select ADO.NET Entity Data Model and name it Northwind.edmx. Generate from Database and select Northwind. Select all the tables and then the designer will generate an ObjectContext called NorthwindEntities and entity classes based on the tables in the database.)&lt;/P&gt;
&lt;P&gt;Because the ObjectContext is what tracks changes on entities you can place entities inside an ObservableCollection but in order for the ObjectContext to be notified that adds and deletes need to be tracked you need to write a bit of code. The easiest thing to do is to create your own class that inherits from ObservableCollection and override the InsertItem and RemoveItem methods so that you can tell the ObjectContext to either add or delete the entity which will ultimately execute against the database. In the constructor pass a reference to the ObjectContext. You can also pass in any collection of entities, say from a LINQ query, and then add them to the ObservableCollection. For example:&lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;Imports &lt;/SPAN&gt;NorthwindDAL
&lt;SPAN style="COLOR: blue"&gt;Imports &lt;/SPAN&gt;System.Collections.ObjectModel

&lt;SPAN style="COLOR: blue"&gt;Public Class &lt;/SPAN&gt;CustomerCollection
    &lt;SPAN style="COLOR: blue"&gt;Inherits &lt;/SPAN&gt;ObservableCollection(&lt;SPAN style="COLOR: blue"&gt;Of &lt;/SPAN&gt;Customer)

   &lt;SPAN style="COLOR: blue"&gt; Private &lt;/SPAN&gt;_context &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;NorthwindEntities
    &lt;SPAN style="COLOR: blue"&gt;Public ReadOnly Property &lt;/SPAN&gt;Context() &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;NorthwindEntities
        &lt;SPAN style="COLOR: blue"&gt;Get
            Return &lt;/SPAN&gt;_context
        &lt;SPAN style="COLOR: blue"&gt;End Get
    End Property

    Sub New&lt;/SPAN&gt;(&lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;customers &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;IEnumerable(&lt;SPAN style="COLOR: blue"&gt;Of &lt;/SPAN&gt;Customer), &lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;context &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;NorthwindEntities)
        &lt;SPAN style="COLOR: blue"&gt;MyBase&lt;/SPAN&gt;.New(customers)&lt;BR&gt;       &lt;SPAN style="COLOR: blue"&gt; &lt;/SPAN&gt;_context = context
    &lt;SPAN style="COLOR: blue"&gt;End Sub

    Protected Overrides Sub &lt;/SPAN&gt;InsertItem(&lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;index &lt;SPAN style="COLOR: blue"&gt;As Integer&lt;/SPAN&gt;, &lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;item &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;Customer)
   &lt;SPAN style="COLOR: blue"&gt;     Me&lt;/SPAN&gt;.Context.AddToCustomers(item)
   &lt;SPAN style="COLOR: blue"&gt;     MyBase&lt;/SPAN&gt;.InsertItem(index, item)
    &lt;SPAN style="COLOR: blue"&gt;End Sub

    Protected Overrides Sub &lt;/SPAN&gt;RemoveItem(&lt;SPAN style="COLOR: blue"&gt;ByVal &lt;/SPAN&gt;index &lt;SPAN style="COLOR: blue"&gt;As Integer&lt;/SPAN&gt;)
        &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.Context.DeleteObject(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;(index))
        &lt;SPAN style="COLOR: blue"&gt;MyBase&lt;/SPAN&gt;.RemoveItem(index)
    &lt;SPAN style="COLOR: blue"&gt;End Sub

End Class&lt;/SPAN&gt;&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;Then you can use the collection on your WPF form instead like so:&lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;Imports &lt;/SPAN&gt;NorthwindDAL

&lt;SPAN style="COLOR: blue"&gt;Class &lt;/SPAN&gt;Window1
    &lt;SPAN style="COLOR: blue"&gt;Private &lt;/SPAN&gt;db &lt;SPAN style="COLOR: blue"&gt;As New &lt;/SPAN&gt;NorthwindEntities
    &lt;SPAN style="COLOR: blue"&gt;Private &lt;/SPAN&gt;CustomerData &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;CustomerCollection
    &lt;SPAN style="COLOR: blue"&gt;Private &lt;/SPAN&gt;View &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;ListCollectionView

    &lt;SPAN style="COLOR: blue"&gt;Private Sub &lt;/SPAN&gt;Window1_Loaded() &lt;SPAN style="COLOR: blue"&gt;Handles MyBase&lt;/SPAN&gt;.Loaded

        &lt;SPAN style="COLOR: blue"&gt;Dim &lt;/SPAN&gt;results = &lt;SPAN style="COLOR: blue"&gt;From &lt;/SPAN&gt;c &lt;SPAN style="COLOR: blue"&gt;In &lt;/SPAN&gt;db.Customers _
                      &lt;SPAN style="COLOR: blue"&gt;Where &lt;/SPAN&gt;c.City.ToLower = &lt;SPAN style="COLOR: #a31515"&gt;"seattle" &lt;/SPAN&gt;_
                      &lt;SPAN style="COLOR: blue"&gt;Order By &lt;/SPAN&gt;c.LastName, c.FirstName _
                      &lt;SPAN style="COLOR: blue"&gt;Select &lt;/SPAN&gt;c

&lt;STRONG&gt;        &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.CustomerData = &lt;SPAN style="COLOR: blue"&gt;New &lt;/SPAN&gt;CustomerCollection(results, db)&lt;/STRONG&gt;&lt;/PRE&gt;&lt;PRE class=code&gt;        &lt;SPAN style="COLOR: blue"&gt;Dim &lt;/SPAN&gt;customerSource = &lt;SPAN style="COLOR: blue"&gt;CType&lt;/SPAN&gt;(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.Resources(&lt;SPAN style="COLOR: #a31515"&gt;"CustomerSource"&lt;/SPAN&gt;), CollectionViewSource)
        customerSource.Source = &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.CustomerData
        &lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.View = &lt;SPAN style="COLOR: blue"&gt;CType&lt;/SPAN&gt;(customerSource.View, ListCollectionView)
    &lt;SPAN style="COLOR: blue"&gt;End Sub&lt;/SPAN&gt;&lt;/PRE&gt;&lt;PRE class=code&gt;    &lt;SPAN style="COLOR: blue"&gt;Private Sub &lt;/SPAN&gt;btnSave_Click() &lt;SPAN style="COLOR: blue"&gt;Handles &lt;/SPAN&gt;btnSave.Click
        &lt;SPAN style="COLOR: blue"&gt;Try
            &lt;/SPAN&gt;db.SaveChanges()
            MsgBox(&lt;SPAN style="COLOR: #a31515"&gt;"Customer data was saved."&lt;/SPAN&gt;)
        &lt;SPAN style="COLOR: blue"&gt;Catch &lt;/SPAN&gt;ex &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;Exception
            MsgBox(ex.ToString())
        &lt;SPAN style="COLOR: blue"&gt;End Try
    End Sub&lt;/SPAN&gt;&lt;/PRE&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;    Private Sub &lt;/SPAN&gt;btnDelete_Click() &lt;SPAN style="COLOR: blue"&gt;Handles &lt;/SPAN&gt;btnDelete.Click
        &lt;SPAN style="COLOR: blue"&gt;If Me&lt;/SPAN&gt;.View.CurrentPosition &amp;gt; -1 &lt;SPAN style="COLOR: blue"&gt;Then
&lt;/SPAN&gt;&lt;SPAN style="COLOR: green"&gt;            &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.View.RemoveAt(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.View.CurrentPosition)
        &lt;SPAN style="COLOR: blue"&gt;End If
    End Sub

    Private Sub &lt;/SPAN&gt;btnAdd_Click() &lt;SPAN style="COLOR: blue"&gt;Handles &lt;/SPAN&gt;btnAdd.Click
&lt;SPAN style="COLOR: blue"&gt;        Dim &lt;/SPAN&gt;customer = &lt;SPAN style="COLOR: blue"&gt;CType&lt;/SPAN&gt;(&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.View.AddNew, Customer)
        &lt;SPAN style="COLOR: green"&gt;'do something with customer if needed...
        &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Me&lt;/SPAN&gt;.View.CommitNew()
    &lt;SPAN style="COLOR: blue"&gt;End Sub&lt;/SPAN&gt;&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;End Class&lt;/SPAN&gt;&lt;/PRE&gt;
&lt;P&gt;Now any updates, adds or deletes you make in the UI will be propagated to the database through the Entity Framework.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Enjoy!&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9597952" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Visual+Basic/default.aspx">Visual Basic</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/WPF/default.aspx">WPF</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/LINQ/default.aspx">LINQ</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/VS2008/default.aspx">VS2008</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/DevCenter/default.aspx">DevCenter</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Article/default.aspx">Article</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Data/default.aspx">Data</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Entity+Framework/default.aspx">Entity Framework</category></item><item><title>Notifying the UI when Entity References Change in Lookup Comboboxes</title><link>http://blogs.msdn.com/bethmassi/archive/2009/05/04/notifying-the-ui-when-entity-references-change-in-lookup-comboboxes.aspx</link><pubDate>Tue, 05 May 2009 05:51:20 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9587373</guid><dc:creator>Beth Massi</dc:creator><slash:comments>6</slash:comments><comments>http://blogs.msdn.com/bethmassi/comments/9587373.aspx</comments><wfw:commentRss>http://blogs.msdn.com/bethmassi/commentrss.aspx?PostID=9587373</wfw:commentRss><wfw:comment>http://blogs.msdn.com/bethmassi/rsscomments.aspx?PostID=9587373</wfw:comment><description>&lt;p&gt;Last week &lt;a href="http://blogs.msdn.com/bethmassi/archive/2009/04/30/data-binding-wpf-lookup-combobox-values-to-ef-entities.aspx" target="_blank"&gt;I wrote about how to data bind WPF lookup comboboxes to entities&lt;/a&gt; returned from the Entity Framework. I described that the key to this type of binding is setting the SelectedItem to the object reference itself on the navigation property instead of setting SelectedValue and SelectedValuePath as in the case when you have foreign key scalar properties like LINQ to SQL classes or DataTables.&lt;/p&gt;  &lt;p&gt;However, depending on your UI, you may need a notification to fire when the entity reference changes. By default this doesn’t happen with entities generated by the &lt;a href="http://msdn.microsoft.com/en-us/library/bb738482.aspx" target="_blank"&gt;EF designer&lt;/a&gt;. Only scalar properties raise change notifications. For instance, going back to our Customer (1)—(*) Order example, the Order entity has a reference to its Customer parent as specified by the navigation property:&lt;/p&gt;  &lt;p&gt;&lt;img src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/DataBindingWPFLookupComboboxValuestoEFEn_F345/image_6.png" /&gt; &lt;/p&gt;  &lt;p&gt;In the database there is a foreign key relationship on CustomerID and that is inferred here by EF. If you look at the Order class that is generated you will see only change notifications raised on the scalar properties, not the navigation properties. For instance, if we take a look at a scalar property that is generated you will see the change notification partial methods generated as well:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Partial Public Class &lt;/span&gt;Order
    &lt;span style="color: blue"&gt;Inherits Global&lt;/span&gt;.System.Data.Objects.DataClasses.EntityObject&lt;br /&gt;.&lt;br /&gt;.&lt;br /&gt;.
    &lt;span style="color: blue"&gt;Public Property &lt;/span&gt;OrderID() &lt;span style="color: blue"&gt;As Integer
        Get
            Return Me&lt;/span&gt;._OrderID
        &lt;span style="color: blue"&gt;End Get
        Set
            Me&lt;/span&gt;.OnOrderIDChanging(value)
            &lt;span style="color: blue"&gt;Me&lt;/span&gt;.ReportPropertyChanging(&lt;span style="color: #a31515"&gt;&amp;quot;OrderID&amp;quot;&lt;/span&gt;)
            &lt;span style="color: blue"&gt;Me&lt;/span&gt;._OrderID = StructuralObject.SetValidValue(value)
            &lt;span style="color: blue"&gt;Me&lt;/span&gt;.ReportPropertyChanged(&lt;span style="color: #a31515"&gt;&amp;quot;OrderID&amp;quot;&lt;/span&gt;)
            &lt;span style="color: blue"&gt;Me&lt;/span&gt;.OnOrderIDChanged
        &lt;span style="color: blue"&gt;End Set
    End Property
    Private &lt;/span&gt;_OrderID &lt;span style="color: blue"&gt;As Integer
    &lt;br /&gt;    Partial Private Sub &lt;/span&gt;OnOrderIDChanging(&lt;span style="color: blue"&gt;ByVal &lt;/span&gt;value &lt;span style="color: blue"&gt;As Integer&lt;/span&gt;)
    &lt;span style="color: blue"&gt;End Sub
    &lt;br /&gt;    Partial Private Sub &lt;/span&gt;OnOrderIDChanged()
    &lt;span style="color: blue"&gt;End Sub
&lt;/span&gt;&lt;br /&gt;.&lt;br /&gt;.&lt;br /&gt;.&lt;/pre&gt;

&lt;p&gt;EF entities that are generated by the designer inherit from &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.objects.dataclasses.entityobject.aspx" target="_blank"&gt;EntityObject&lt;/a&gt; that in turn inherits from &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.objects.dataclasses.structuralobject.aspx" target="_blank"&gt;StructuralObject&lt;/a&gt; that implements&amp;#160; &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx" target="_blank"&gt;INotifyPropertyChanged&lt;/a&gt;. This interface is necessary for notifying the UI (WPF and Winforms) that data bound controls should refresh their value. So say you programmatically change a scalar property then any controls bound to that property will be refreshed with the new value automatically. Or in many cases you have a UI with multiple controls bound to the same property. If the user makes a change to one control, the rest update automatically. &lt;/p&gt;

&lt;p&gt;However this notification isn’t generated on entity references. Which means that if you have a lookup combobox set up &lt;a href="http://blogs.msdn.com/bethmassi/archive/2009/04/30/data-binding-wpf-lookup-combobox-values-to-ef-entities.aspx" target="_blank"&gt;like I described in last week’s post&lt;/a&gt; and also have another control bound to the same Customer navigation property, then it won’t refresh properly. &lt;/p&gt;

&lt;p&gt;For instance, say we have an Order form with a combobox &lt;a href="http://blogs.msdn.com/bethmassi/archive/2009/04/30/data-binding-wpf-lookup-combobox-values-to-ef-entities.aspx" target="_blank"&gt;set up like before&lt;/a&gt;, where the SelectedItem is bound to the Customer property (SelectedItem=&amp;quot;{Binding Path=Customer}&amp;quot;), but we also have a listbox that shows OrderDate, Customer.LastName, Customer.FirstName:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/NotifyingtheUIwhenEntityReferencesChange_1085D/image_2.png"&gt;&lt;img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="302" alt="image" src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/NotifyingtheUIwhenEntityReferencesChange_1085D/image_thumb.png" width="468" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;ListBox &lt;/span&gt;&lt;span style="color: red"&gt;Grid.Row&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;1&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;ListBox1&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;ItemsSource&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding&lt;/span&gt;&lt;span style="color: blue"&gt;}&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;IsSynchronizedWithCurrentItem&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;True&amp;quot;&amp;gt;
&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;ItemsControl.ItemTemplate&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
        &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel &lt;/span&gt;&lt;span style="color: red"&gt;Orientation&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Horizontal&amp;quot;&amp;gt;
            &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock &lt;/span&gt;&lt;span style="color: red"&gt;Width&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;60&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Text&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;Path&lt;/span&gt;&lt;span style="color: blue"&gt;=OrderDate, &lt;/span&gt;&lt;span style="color: red"&gt;StringFormat&lt;/span&gt;&lt;span style="color: blue"&gt;='d'}&amp;quot; /&amp;gt;
            &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock &lt;/span&gt;&lt;span style="color: red"&gt;Text&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Customer.LastName}&amp;quot; /&amp;gt;
            &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock &lt;/span&gt;&lt;span style="color: red"&gt;Width&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;5&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;, &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
            &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock &lt;/span&gt;&lt;span style="color: red"&gt;Text&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Customer.FirstName}&amp;quot; /&amp;gt;
        &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;ItemsControl.ItemTemplate&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;If the user changes the OrderDate then that change will automatically be reflected in the listbox. But if the user changes the Customer in the dropdown combobox then it will NOT update the listbox because a change notification is not raised on Customer. What’s also interesting is if you look at that part of the generated Order entity then you will actually see &lt;strong&gt;two&lt;/strong&gt; properties, one we expect called Customer and one called CustomerReference:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;.&lt;br /&gt;.&lt;br /&gt;.&lt;br /&gt;Public Property &lt;/span&gt;Customer() &lt;span style="color: blue"&gt;As &lt;/span&gt;Customer
    &lt;span style="color: blue"&gt;Get
        Return CType&lt;/span&gt;(&lt;span style="color: blue"&gt;Me&lt;/span&gt;, IEntityWithRelationships).RelationshipManager. _
        GetRelatedReference(&lt;span style="color: blue"&gt;Of &lt;/span&gt;Customer)(&lt;span style="color: #a31515"&gt;&amp;quot;OMSModel.FK_Orders_Customer&amp;quot;&lt;/span&gt;, &lt;span style="color: #a31515"&gt;&amp;quot;Customer&amp;quot;&lt;/span&gt;).Value
    &lt;span style="color: blue"&gt;End Get
    Set&lt;/span&gt;(&lt;span style="color: blue"&gt;ByVal &lt;/span&gt;value &lt;span style="color: blue"&gt;As &lt;/span&gt;Customer)
        &lt;span style="color: blue"&gt;CType&lt;/span&gt;(&lt;span style="color: blue"&gt;Me&lt;/span&gt;, IEntityWithRelationships).RelationshipManager. _
        GetRelatedReference(&lt;span style="color: blue"&gt;Of &lt;/span&gt;Customer)(&lt;span style="color: #a31515"&gt;&amp;quot;OMSModel.FK_Orders_Customer&amp;quot;&lt;/span&gt;, &lt;span style="color: #a31515"&gt;&amp;quot;Customer&amp;quot;&lt;/span&gt;).Value = value
    &lt;span style="color: blue"&gt;End Set
End Property&lt;br /&gt;.&lt;br /&gt;.&lt;br /&gt;.
Public Property &lt;/span&gt;CustomerReference() &lt;span style="color: blue"&gt;As &lt;/span&gt;EntityReference(&lt;span style="color: blue"&gt;Of &lt;/span&gt;Customer)
    &lt;span style="color: blue"&gt;Get
        Return CType&lt;/span&gt;(&lt;span style="color: blue"&gt;Me&lt;/span&gt;, IEntityWithRelationships).RelationshipManager. _
        GetRelatedReference(&lt;span style="color: blue"&gt;Of &lt;/span&gt;Customer)(&lt;span style="color: #a31515"&gt;&amp;quot;OMSModel.FK_Orders_Customer&amp;quot;&lt;/span&gt;, &lt;span style="color: #a31515"&gt;&amp;quot;Customer&amp;quot;&lt;/span&gt;)
    &lt;span style="color: blue"&gt;End Get
    Set&lt;/span&gt;(&lt;span style="color: blue"&gt;ByVal &lt;/span&gt;value &lt;span style="color: blue"&gt;As &lt;/span&gt;EntityReference(&lt;span style="color: blue"&gt;Of &lt;/span&gt;Customer))
        &lt;span style="color: blue"&gt;If &lt;/span&gt;(&lt;span style="color: blue"&gt;Not &lt;/span&gt;(value) &lt;span style="color: blue"&gt;Is Nothing&lt;/span&gt;) &lt;span style="color: blue"&gt;Then
            CType&lt;/span&gt;(&lt;span style="color: blue"&gt;Me&lt;/span&gt;, IEntityWithRelationships).RelationshipManager. _
            InitializeRelatedReference(&lt;span style="color: blue"&gt;Of &lt;/span&gt;Customer)(&lt;span style="color: #a31515"&gt;&amp;quot;OMSModel.FK_Orders_Customer&amp;quot;&lt;/span&gt;, &lt;span style="color: #a31515"&gt;&amp;quot;Customer&amp;quot;&lt;/span&gt;, value)
        &lt;span style="color: blue"&gt;End If
    End Set
End Property&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The Customer property is a navigation property to the parent Customer entity itself as we expect. The CustomerReference is an &lt;a href="http://msdn.microsoft.com/en-us/library/bb297956.aspx" target="_blank"&gt;EntityReference&lt;/a&gt; class. This class describes the &lt;strong&gt;relationship&lt;/strong&gt; between the Order and Customer. It also defines an event called &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.objects.dataclasses.relatedend.associationchanged.aspx" target="_blank"&gt;AssociationChanged&lt;/a&gt; that you can handle to notify the UI properly when the reference changes. When you change the reference this event will fire twice, first to remove the old reference and then again to add the new one. You can easily extend the Order partial class by creating another &lt;a href="http://msdn.microsoft.com/en-us/library/yfzd5350.aspx" target="_blank"&gt;Partial Class declaration&lt;/a&gt; for Order in the same namespace (which is automatically imported in VB) and then calling the appropriate property change notifications:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Imports &lt;/span&gt;System.ComponentModel

&lt;span style="color: blue"&gt;Partial Public Class &lt;/span&gt;Order
    &lt;span style="color: blue"&gt;Sub New&lt;/span&gt;()
        &lt;span style="color: blue"&gt;MyBase&lt;/span&gt;.New()
        &lt;span style="color: blue"&gt;AddHandler Me&lt;/span&gt;.CustomerReference.AssociationChanged, &lt;span style="color: blue"&gt;AddressOf &lt;/span&gt;Customer_AssociationChanged
    &lt;span style="color: blue"&gt;End Sub

    Private Sub &lt;/span&gt;Customer_AssociationChanged(&lt;span style="color: blue"&gt;ByVal &lt;/span&gt;sender &lt;span style="color: blue"&gt;As Object&lt;/span&gt;, _
                                            &lt;span style="color: blue"&gt;ByVal &lt;/span&gt;e &lt;span style="color: blue"&gt;As &lt;/span&gt;CollectionChangeEventArgs)
        &lt;span style="color: blue"&gt;If &lt;/span&gt;e.Action = CollectionChangeAction.Remove &lt;span style="color: blue"&gt;Then
            &lt;/span&gt;OnPropertyChanging(&lt;span style="color: #a31515"&gt;&amp;quot;Customer&amp;quot;&lt;/span&gt;)
        &lt;span style="color: blue"&gt;Else
            &lt;/span&gt;OnPropertyChanged(&lt;span style="color: #a31515"&gt;&amp;quot;Customer&amp;quot;&lt;/span&gt;)
        &lt;span style="color: blue"&gt;End If
    End Sub
End Class&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;So now we can change the Customer in the dropdown and the UI will be notified properly. Sweet. For more information on Entity Framework and data binding &lt;a href="http://msdn.microsoft.com/en-us/library/bb738469.aspx" target="_blank"&gt;see this topic in the MSDN library&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Enjoy!&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9587373" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Visual+Basic/default.aspx">Visual Basic</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/WPF/default.aspx">WPF</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/VS2008/default.aspx">VS2008</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/DevCenter/default.aspx">DevCenter</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Article/default.aspx">Article</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Data/default.aspx">Data</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Entity+Framework/default.aspx">Entity Framework</category></item><item><title>Data Binding WPF Lookup Combobox Values to EF Entities</title><link>http://blogs.msdn.com/bethmassi/archive/2009/04/30/data-binding-wpf-lookup-combobox-values-to-ef-entities.aspx</link><pubDate>Thu, 30 Apr 2009 17:57:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9576176</guid><dc:creator>Beth Massi</dc:creator><slash:comments>5</slash:comments><comments>http://blogs.msdn.com/bethmassi/comments/9576176.aspx</comments><wfw:commentRss>http://blogs.msdn.com/bethmassi/commentrss.aspx?PostID=9576176</wfw:commentRss><wfw:comment>http://blogs.msdn.com/bethmassi/rsscomments.aspx?PostID=9576176</wfw:comment><description>&lt;p&gt;It’s extremely common to have to hook up lookup tables on your data entry forms in order to populate foreign keys in a database. I’ve talked about how to do this in Winforms and WPF with Datasets and LINQ to SQL before:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/vbasic/cc788742.aspx" target="_blank"&gt;How Do I: Create a Lookup Combobox in WPF?&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/vbasic/dd239277.aspx" target="_blank"&gt;How Do I: Create a Master-Detail Data Entry Form in WPF?&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/vbasic/bb643829.aspx" target="_blank"&gt;How Do I: Create Lookup Lists?&lt;/a&gt;&amp;#160; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/bethmassi/archive/2008/02/07/creating-lookup-lists-with-linq-to-sql.aspx"&gt;Creating Lookup Lists with LINQ to SQL&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/bethmassi/archive/2008/02/06/related-data-binding-and-comboboxes-with-linq-to-sql.aspx"&gt;Related Data Binding and ComboBoxes with LINQ to SQL&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://blogs.msdn.com/bethmassi/archive/2007/04/25/tips-on-related-data-binding-and-comboboxes.aspx"&gt;Tips on Related Data Binding and ComboBoxes&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The common theme between all of these is that the data sources, either the LINQ to SQL classes or the DataTables that we bind to, uses a navigation path based on the foreign key and that foreign key is exposed as a property (or DataColumn). For instance if we have a Customer related to Orders we would have a CustomerID property on Orders. &lt;/p&gt;  &lt;p&gt;DataSets (like databases) rely on this type of navigation. So when you want to find the parent Customer of an Order you have to know the relation. Using typed datasets helps you more but you still end up having to know the details of relationships and foreign keys of the DataSet. That’s why people who are familiar with databases are usually comfortable with working with DataSets.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/DataBindingWPFLookupComboboxValuestoEFEn_F345/image_2.png"&gt;&lt;img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="236" alt="image" src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/DataBindingWPFLookupComboboxValuestoEFEn_F345/image_thumb.png" width="587" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;LINQ to SQL classes also include navigation properties as direct object references and collections. So they have both the foreign key and the navigation properties. Customer will have a collection of Orders and Order will have a reference back to Customer but the classes also contain the CustomerID property. This isn’t “pure” I suppose but it does make data binding and subsequent saves back to the database pretty much a no brainer. &lt;/p&gt;  &lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/DataBindingWPFLookupComboboxValuestoEFEn_F345/image_4.png"&gt;&lt;img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="242" alt="image" src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/DataBindingWPFLookupComboboxValuestoEFEn_F345/image_thumb_1.png" width="553" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;For instance say I want to hook up a lookup combobox using a LINQ to SQL class on an Order with a reference to Customer. I want to display a list of Customers the user can pick from and that Customer should be associated with that Order. It’s pretty straight forward and works the same with DataTables.&lt;/p&gt;  &lt;p&gt;XAML:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;Window.Resources&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;CollectionViewSource &lt;/span&gt;&lt;span style="color: red"&gt;x&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;Key&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;OrdersSource&amp;quot; /&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;CollectionViewSource &lt;/span&gt;&lt;span style="color: red"&gt;x&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;Key&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;CustomerLookup&amp;quot; /&amp;gt;
&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;Window.Resources&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;Grid &lt;/span&gt;&lt;span style="color: red"&gt;Grid.Row&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;1&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Grid1&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;DataContext&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;Source&lt;/span&gt;&lt;span style="color: blue"&gt;={&lt;/span&gt;&lt;span style="color: #a31515"&gt;StaticResource &lt;/span&gt;&lt;span style="color: red"&gt;OrdersSource&lt;/span&gt;&lt;span style="color: blue"&gt;}}&amp;quot;&amp;gt;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;&amp;lt;ComboBox &lt;/span&gt;&lt;span style="color: red"&gt;Height&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;23&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;ComboBox1&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Width&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;177&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Margin&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;2&amp;quot;  &lt;/span&gt;&lt;span style="color: red"&gt;HorizontalAlignment&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Left&amp;quot; 
          &lt;/span&gt;&lt;span style="color: red"&gt;IsEditable&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;False&amp;quot;
          &lt;/span&gt;&lt;span style="color: red"&gt;ItemsSource&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;Source&lt;/span&gt;&lt;span style="color: blue"&gt;={&lt;/span&gt;&lt;span style="color: #a31515"&gt;StaticResource &lt;/span&gt;&lt;span style="color: red"&gt;CustomerLookup&lt;/span&gt;&lt;span style="color: blue"&gt;}}&amp;quot;&lt;br /&gt;&lt;/span&gt;&lt;span style="color: red"&gt;          DisplayMemberPath&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;LastName&amp;quot;&lt;br /&gt;&lt;span style="color: red"&gt;          SelectedValuePath&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;CustomerID&amp;quot; &lt;/span&gt;&lt;/span&gt;&lt;span style="color: blue"&gt;
&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;          &lt;/span&gt;&lt;span style="color: red"&gt;SelectedValue&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;Path&lt;/span&gt;&lt;span style="color: blue"&gt;=CustomerID}&amp;quot; 
          &lt;/span&gt;&lt;span style="color: blue"&gt;/&amp;gt;&lt;br /&gt;...&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Code-behind:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Class &lt;/span&gt;Window1
    &lt;span style="color: blue"&gt;Private &lt;/span&gt;db &lt;span style="color: blue"&gt;As New &lt;/span&gt;MyDataObjectContext
    &lt;span style="color: blue"&gt;Private &lt;/span&gt;OrderData &lt;span style="color: blue"&gt;As &lt;/span&gt;IEnumerable(&lt;span style="color: blue"&gt;Of &lt;/span&gt;Order)

    &lt;span style="color: blue"&gt;Private Sub &lt;/span&gt;Window1_Loaded(&lt;span style="color: blue"&gt;ByVal &lt;/span&gt;sender &lt;span style="color: blue"&gt;As Object&lt;/span&gt;, &lt;span style="color: blue"&gt;ByVal &lt;/span&gt;e &lt;span style="color: blue"&gt;As &lt;/span&gt;System.Windows.RoutedEventArgs) &lt;span style="color: blue"&gt;Handles Me&lt;/span&gt;.Loaded
        &lt;span style="color: green"&gt;'Load all the orders from the database
        &lt;/span&gt;&lt;span style="color: blue"&gt;Me&lt;/span&gt;.OrderData = db.Orders
        &lt;span style="color: green"&gt;'Get the customer lookup list (this is the Combobox ItemsSource)
        &lt;/span&gt;&lt;span style="color: blue"&gt;Dim &lt;/span&gt;customerList = &lt;span style="color: blue"&gt;From &lt;/span&gt;c &lt;span style="color: blue"&gt;In &lt;/span&gt;db.Customers _
                           &lt;span style="color: blue"&gt;Where &lt;/span&gt;c.Orders.Count &amp;gt; 0 _
                           &lt;span style="color: blue"&gt;Order By &lt;/span&gt;c.LastName, c.FirstName

        &lt;span style="color: blue"&gt;Dim &lt;/span&gt;ordersSource = &lt;span style="color: blue"&gt;CType&lt;/span&gt;(&lt;span style="color: blue"&gt;Me&lt;/span&gt;.FindResource(&lt;span style="color: #a31515"&gt;&amp;quot;OrdersSource&amp;quot;&lt;/span&gt;), CollectionViewSource)
        ordersSource.Source = &lt;span style="color: blue"&gt;Me&lt;/span&gt;.OrderData
        &lt;span style="color: blue"&gt;Dim &lt;/span&gt;custSource = &lt;span style="color: blue"&gt;CType&lt;/span&gt;(&lt;span style="color: blue"&gt;Me&lt;/span&gt;.FindResource(&lt;span style="color: #a31515"&gt;&amp;quot;CustomerLookup&amp;quot;&lt;/span&gt;), CollectionViewSource)
        custSource.Source = customerList.ToList()

    &lt;span style="color: blue"&gt;End Sub&lt;br /&gt;...&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Almost all of this code is just to set up the context of this discussion, you can &lt;a href="http://msdn.microsoft.com/en-us/vbasic/dd239277.aspx" target="_blank"&gt;watch this video for details&lt;/a&gt; on building a complete example. Here I’m using CollectionViewSources in the XAML and setting their Source property in code. This technique is handy especially if you are using nested DataTemplates. The important piece to note are the four properties on the Combobox. ItemsSource, DisplayMemberPath, SelectedValue, and SelectedValuePath. To set up your combobox:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Set the ItemsSource to the list of Customers you want to display in the Combobox.&amp;#160; &lt;/li&gt;

  &lt;li&gt;Next set the DisplayMemberPath to the property name on this list that you want to use to display in the list, here I used LastName. &lt;/li&gt;

  &lt;li&gt;Then set the &lt;strong&gt;SelectedValuePath &lt;/strong&gt;to the property name on this list that will be used to populate the foreign key value on the Order. &lt;/li&gt;

  &lt;li&gt;Finally you set the &lt;strong&gt;SelectedValue&lt;/strong&gt; to the property binding on the Order that is foreign key. LINQ to SQL (and DataSets) will happily save your data with this binding in place. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This is how you always bind DataTables and it also works well for LINQ to SQL classes. But since LINQ to SQL classes also include the navigation properties (the Orders collection on Customer and the Customer object reference on Order) you can use a different technique by binding directly to the Customer reference. This is the only choice we have with Entity Framework entities in .NET 3.5 SP1. &lt;/p&gt;

&lt;p&gt;What’s unique with Entity Framework is that the associations between other entities use &lt;strong&gt;only &lt;/strong&gt;navigation properties -- so there isn’t a CustomerID foreign key property value on the Order at all. &lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/DataBindingWPFLookupComboboxValuestoEFEn_F345/image_6.png"&gt;&lt;img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="279" alt="image" src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/DataBindingWPFLookupComboboxValuestoEFEn_F345/image_thumb_2.png" width="448" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;What you have to do instead is &lt;strong&gt;bind directly to the Customer &lt;/strong&gt;object reference. The change in the above example is the Combobox binding in XAML:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;ComboBox &lt;/span&gt;&lt;span style="color: red"&gt;Height&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;23&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Name&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;ComboBox1&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Width&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;177&amp;quot; &lt;/span&gt;&lt;span style="color: red"&gt;Margin&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;2&amp;quot;  &lt;/span&gt;&lt;span style="color: red"&gt;HorizontalAlignment&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;Left&amp;quot; 
          &lt;/span&gt;&lt;span style="color: red"&gt;IsEditable&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;False&amp;quot;
          &lt;/span&gt;&lt;span style="color: red"&gt;ItemsSource&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;Source&lt;/span&gt;&lt;span style="color: blue"&gt;={&lt;/span&gt;&lt;span style="color: #a31515"&gt;StaticResource &lt;/span&gt;&lt;span style="color: red"&gt;CustomerLookup&lt;/span&gt;&lt;span style="color: blue"&gt;}}&amp;quot;
&lt;span style="color: red"&gt;          DisplayMemberPath&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;LastName&amp;quot;&lt;/span&gt;          &lt;br /&gt;&lt;/span&gt;&lt;span style="color: red"&gt;          SelectedItem&lt;/span&gt;&lt;span style="color: blue"&gt;=&amp;quot;{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding &lt;/span&gt;&lt;span style="color: red"&gt;Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Customer}&amp;quot; 
          &lt;/span&gt;&lt;span style="color: blue"&gt;/&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The important pieces in this case are the three properties on the Combobox. ItemsSource, DisplayMemberPath, and &lt;strong&gt;SelectedItem&lt;/strong&gt;. &lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Set the ItemsSource to the list of Customers you want to display in the Combobox -- same as before. &lt;/li&gt;

  &lt;li&gt;Next set the DisplayMemberPath to the property name on this list that you want to use to display in the list, here I used LastName – same as before. &lt;/li&gt;

  &lt;li&gt;Now set the &lt;strong&gt;SelectedItem&lt;/strong&gt; to the property binding on the Order that is the &lt;strong&gt;navigation property to Customer&lt;/strong&gt;. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This will work properly with LINQ to SQL classes and Entity Framework entities but there is one caveat. You need to make sure that you pull the &lt;strong&gt;entire Customer entity &lt;/strong&gt;into in the lookup list &lt;strong&gt;from the same ObjectContext &lt;/strong&gt;you used to query the Orders. This is because the same ObjectContext (DataContext in LINQ to SQL) needs to resolve the entity references between the queries. Entity Framework does this based on the EntityKeys. The neat side effect of this with EF is that you don’t have to pull down the Customers with the Orders query, they will automatically become references when the Customer lookup list is queried through the same context. (See &lt;a href="http://blogs.msdn.com/bethmassi/archive/2008/12/10/master-details-with-entity-framework-explicit-load.aspx" target="_blank"&gt;my post on explicit load for more details&lt;/a&gt; on how to bring down related EF entities when you only make one call.)&lt;/p&gt;

&lt;p&gt;This behavior may be desired in a lot of scenarios but if we do not need to modify the Customer, like in our example, this can be overkill especially if the Customer has a lot of large fields you aren’t using. In the first example we could have only pulled a subset of fields from the Customer table – the only required ones would be the ones used in the data binding, CustomerID and LastName. So with DataTables and LINQ to SQL classes that bind on the values we could have optimized our lookup list query to:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Dim &lt;/span&gt;customerList = &lt;span style="color: blue"&gt;From &lt;/span&gt;c &lt;span style="color: blue"&gt;In &lt;/span&gt;db.Customers _
                   &lt;span style="color: blue"&gt;Where &lt;/span&gt;c.Orders.Count &amp;gt; 0 _
                   &lt;span style="color: blue"&gt;Order By &lt;/span&gt;c.LastName, c.FirstName _
                   &lt;span style="color: blue"&gt;Select &lt;/span&gt;c.CustomerID, c.LastName&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This &lt;strong&gt;will not work &lt;/strong&gt;if we bind directly to the navigation properties because the customerList is now a list of anonymous types and not a list of Customer entities. So binding to the values gives you greater flexibility with your lookup list queries. Unfortunately in the current version of EF you cannot bind this way but they are planning to enable this in the next version. In .NET 4.0 the EF team will add support for a new type of association called &amp;quot;FK Associations&amp;quot;. &lt;a href="http://blogs.msdn.com/efdesign/archive/2009/03/16/foreign-keys-in-the-entity-framework.aspx" target="_blank"&gt;Read more about that here.&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And I’m working on the next set of &lt;a href="http://msdn.microsoft.com/en-us/vbasic/bb466226.aspx#wpfdata" target="_blank"&gt;WPF Forms over Data How Do I videos&lt;/a&gt;, this time with Entity Framework, that will hopefully explain how to use EF in practical way by building WPF data applications. Stay tuned!&lt;/p&gt;

&lt;p&gt;Enjoy!&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9576176" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Visual+Basic/default.aspx">Visual Basic</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/WPF/default.aspx">WPF</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/LINQ/default.aspx">LINQ</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/VS2008/default.aspx">VS2008</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/DevCenter/default.aspx">DevCenter</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Article/default.aspx">Article</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Data/default.aspx">Data</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Entity+Framework/default.aspx">Entity Framework</category></item><item><title>Tally Rows in a DataSet that Match a Condition</title><link>http://blogs.msdn.com/bethmassi/archive/2009/04/27/tally-rows-in-a-dataset-that-match-a-condition.aspx</link><pubDate>Tue, 28 Apr 2009 05:24:21 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9572773</guid><dc:creator>Beth Massi</dc:creator><slash:comments>8</slash:comments><comments>http://blogs.msdn.com/bethmassi/comments/9572773.aspx</comments><wfw:commentRss>http://blogs.msdn.com/bethmassi/commentrss.aspx?PostID=9572773</wfw:commentRss><wfw:comment>http://blogs.msdn.com/bethmassi/rsscomments.aspx?PostID=9572773</wfw:comment><description>&lt;p&gt;Today I got a question that comes up often in data application programming about how to count rows in a DataSet that matched a condition. The DataSet may be bound to a DataGridView or other list control and it’s tempting to start looking at the control to see if you can coax it into returning what you need but usually there is a much better way.&lt;/p&gt;  &lt;p&gt;For instance, say we have a table in our database called “Inbox” that has varchar fields Subject, From, and Status and we’d like to tally all the rows where the Status = “Unread”. Suppose we’ve also created a typed DataSet that contains this Inbox table. You create a data-bound Windows Form with a DataGridView on it by dragging the table from the Data sources window onto the form (&lt;a href="http://msdn.microsoft.com/en-us/vbasic/bb725824.aspx"&gt;like I showed in this video&lt;/a&gt;). When you do this, Visual Studio generates code that hooks up your DataGridView’s DataSource property to a BindingSource object which in turn has it’s DataSource set to your DataSet. This is a good thing. The BindingSource is a simple controller that provides currency between your DataSet and the DataGidView UI. (In WPF this is similar to the CollectionView object). You write code against the BindingSource instead so that it doesn’t matter what kind of control is being used to display the data.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;BindingSource to the Rescue&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;The BindingSource in this case is actually working with a DataView, not the actual DataTable, which may seem confusing. This is needed for related data binding to work (see &lt;a href="http://msdn.microsoft.com/en-us/vbasic/bb643827.aspx"&gt;this video&lt;/a&gt; and &lt;a href="http://msdn.microsoft.com/en-us/vbasic/cc138241.aspx"&gt;this one&lt;/a&gt;). Since the BindingSource manages the currency (current row position) that is being displayed by the controls, in this example the BindingSource.List will return the DataView and the BindingSource.Current property will always return the DataRowView. You access your typed DataRow by casting the DataRowView.Row property. So to get a count of items in the DataView we could just simply ask the BindingSource for a count of it’s rows no matter what kind of control is being used for the display:&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Dim &lt;/span&gt;count = &lt;span style="color: blue"&gt;Me&lt;/span&gt;.InboxBindingSource.Count&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Or we could grab the DataView and ask for its count:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Dim &lt;/span&gt;dv = &lt;span style="color: blue"&gt;CType&lt;/span&gt;(&lt;span style="color: blue"&gt;Me&lt;/span&gt;.InboxBindingSource.List, DataView)
&lt;span style="color: blue"&gt;Dim &lt;/span&gt;count = dv.Count&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Once you have the DataView you can apply more filtering on it directly or we can loop through it to tally the rows where Status = “Unread”. &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Dim &lt;/span&gt;dv = &lt;span style="color: blue"&gt;CType&lt;/span&gt;(&lt;span style="color: blue"&gt;Me&lt;/span&gt;.InboxBindingSource.List, DataView)
&lt;span style="color: blue"&gt;Dim &lt;/span&gt;count = 0
&lt;span style="color: blue"&gt;For Each &lt;/span&gt;drv &lt;span style="color: blue"&gt;As &lt;/span&gt;DataRowView &lt;span style="color: blue"&gt;In &lt;/span&gt;dv
    &lt;span style="color: blue"&gt;Dim &lt;/span&gt;inboxRow = &lt;span style="color: blue"&gt;CType&lt;/span&gt;(drv.Row, EmailDataSet.InboxRow)
    &lt;span style="color: blue"&gt;If &lt;/span&gt;inboxRow.Status = &lt;span style="color: #a31515"&gt;&amp;quot;Unread&amp;quot; &lt;/span&gt;&lt;span style="color: blue"&gt;Then
        &lt;/span&gt;count += 1
    &lt;span style="color: blue"&gt;End If
Next&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;But the neat thing about using the BindingSource is that you always know the current row being displayed. So if we want to tally the rows based on a condition in the current row we go through the BindingSource. You can easily write the code that gets the current row as your typed data row by using a code snippet. Right-click in the editor, select Data – LINQ, XML, Designer, ADO.NET &amp;gt; Designer Features and ADO.NET &amp;gt; Converts BindingSource.Current to a specific row in a DataTable:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/TallyRowsinaDataSetthatMatchaCondition_110E1/image_4.png"&gt;&lt;img title="image" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="211" alt="image" src="http://blogs.msdn.com/blogfiles/bethmassi/WindowsLiveWriter/TallyRowsinaDataSetthatMatchaCondition_110E1/image_thumb_1.png" width="709" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;This code returns a tally of rows in the current view that have the same status as the selected row. Instead of looping through the data manually with For Each, this code sets the Filter property of the DataView instead:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Dim &lt;/span&gt;currentRow &lt;span style="color: blue"&gt;As &lt;/span&gt;EmailDataSet.InboxRow
currentRow = &lt;span style="color: blue"&gt;CType&lt;/span&gt;(&lt;span style="color: blue"&gt;CType&lt;/span&gt;(&lt;span style="color: blue"&gt;Me&lt;/span&gt;.InboxBindingSource.Current, DataRowView).Row, EmailDataSet.InboxRow)

&lt;span style="color: blue"&gt;Dim &lt;/span&gt;dv = &lt;span style="color: blue"&gt;CType&lt;/span&gt;(&lt;span style="color: blue"&gt;Me&lt;/span&gt;.InboxBindingSource.List, DataView)
dv.RowFilter = &lt;span style="color: #a31515"&gt;&amp;quot;Status ='&amp;quot; &lt;/span&gt;&amp;amp; currentRow.Status &amp;amp; &lt;span style="color: #a31515"&gt;&amp;quot;'&amp;quot;
&lt;/span&gt;&lt;span style="color: blue"&gt;Dim &lt;/span&gt;count = dv.Count&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This technique causes any bound controls to update to the new filter. To remove the filter, set the Filter property to Nothing or the empty string. Although this code may work for a lot of scenarios, we may have a situation where we do not want to affect any of the bound controls by changing the filter. And even though this is a simple condition it would be nice not to have to manually write the loop ourselves. This is a perfect place to use LINQ instead. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;LINQ to the Rescue&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If we want to tally the entire DataTable for rows matching a condition we can use LINQ to DataSets with Visual Basic’s Aggregate clause. This doesn’t involve a BindingSource at all but be aware that the DataView that a BindingSource may be displaying data from may be filtered. In the case of this example the DataView contains the same rows as the DataTable (no filter) so we can write a simple Aggregate query to count the rows:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Dim &lt;/span&gt;count &lt;span style="color: blue"&gt;As Integer &lt;/span&gt;= &lt;span style="color: blue"&gt;Aggregate &lt;/span&gt;row &lt;span style="color: blue"&gt;In Me&lt;/span&gt;.EmailDataSet.Inbox _
                       &lt;span style="color: blue"&gt;Where &lt;/span&gt;row.Status = &lt;span style="color: #a31515"&gt;&amp;quot;Unread&amp;quot; &lt;/span&gt;_
                       &lt;span style="color: blue"&gt;Into &lt;/span&gt;UnreadCount = Count()&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;This will return an integer indicating the number of rows in the entire DataTable that matched the Where clause. But what if we do want to use the BindingSource and take into account any filters that are being applied to the DataView in which controls are bound? In this case we can still use an Aggregate LINQ query it will just be against the DataView so we will need to cast a few things:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Dim &lt;/span&gt;dv = &lt;span style="color: blue"&gt;CType&lt;/span&gt;(&lt;span style="color: blue"&gt;Me&lt;/span&gt;.InboxBindingSource.List, DataView)
&lt;span style="color: blue"&gt;Dim &lt;/span&gt;count &lt;span style="color: blue"&gt;As Integer &lt;/span&gt;= &lt;span style="color: blue"&gt;Aggregate &lt;/span&gt;row &lt;span style="color: blue"&gt;In &lt;/span&gt;dv.Cast(&lt;span style="color: blue"&gt;Of &lt;/span&gt;DataRowView).AsQueryable _
                       &lt;span style="color: blue"&gt;Where CType&lt;/span&gt;(row.Row, EmailDataSet.InboxRow).Status = &lt;span style="color: #a31515"&gt;&amp;quot;Unread&amp;quot; &lt;/span&gt;_
                       &lt;span style="color: blue"&gt;Into &lt;/span&gt;UnreadCount = Count()&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Now what would be really nice is to automatically tally this information from the DataSet and display it in a label on the Form anytime the user made any changes to the rows. We can do this easily by handling the BindingSource’s ListChanged event and putting our Aggregate LINQ query in there:&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Private Sub &lt;/span&gt;InboxBindingSource_ListChanged() &lt;span style="color: blue"&gt;Handles &lt;/span&gt;InboxBindingSource.ListChanged
    &lt;span style="color: blue"&gt;Dim &lt;/span&gt;count &lt;span style="color: blue"&gt;As Integer &lt;/span&gt;= &lt;span style="color: blue"&gt;Aggregate &lt;/span&gt;row &lt;span style="color: blue"&gt;In Me&lt;/span&gt;.EmailDataSet.Inbox _
                           &lt;span style="color: blue"&gt;Where &lt;/span&gt;row.Status = &lt;span style="color: #a31515"&gt;&amp;quot;Unread&amp;quot; &lt;/span&gt;_
                           &lt;span style="color: blue"&gt;Into &lt;/span&gt;UnreadCount = Count()

    &lt;span style="color: blue"&gt;Me&lt;/span&gt;.lblStatus.Text = count.ToString() &amp;amp; &lt;span style="color: #a31515"&gt;&amp;quot; unread email.&amp;quot;
&lt;/span&gt;&lt;span style="color: blue"&gt;End Sub&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Now this will give us a “live” running tally and we’re not bound to the UI controls at all. Nice. For more information on Aggregate queries and DataSets &lt;a href="http://msdn.microsoft.com/en-us/vbasic/bb737877.aspx"&gt;check out this video&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;More resources:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/bb531251.aspx"&gt;Visual Basic Aggregate Clause&lt;/a&gt;&lt;/li&gt;

  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/vbasic/bb688088.aspx"&gt;101 Visual Basic LINQ Samples&lt;/a&gt;&lt;/li&gt;

  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/vbasic/bb737877.aspx"&gt;How Do I: LINQ over DataSets?&lt;/a&gt;&lt;/li&gt;

  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/vbasic/bb725824.aspx"&gt;How Do I: Understand Data?&lt;/a&gt;&lt;/li&gt;

  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/vbasic/cc138241.aspx"&gt;How Do I: Update Related Tables?&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Enjoy!&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9572773" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Visual+Basic/default.aspx">Visual Basic</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/LINQ/default.aspx">LINQ</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Winforms/default.aspx">Winforms</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/DevCenter/default.aspx">DevCenter</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Article/default.aspx">Article</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Data/default.aspx">Data</category></item><item><title>Channel 9 Interview: WPF Improvements in VS2010 for Business Apps</title><link>http://blogs.msdn.com/bethmassi/archive/2009/03/24/channel-9-interview-wpf-improvements-in-vs2010-for-business-apps.aspx</link><pubDate>Tue, 24 Mar 2009 19:01:08 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9504586</guid><dc:creator>Beth Massi</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/bethmassi/comments/9504586.aspx</comments><wfw:commentRss>http://blogs.msdn.com/bethmassi/commentrss.aspx?PostID=9504586</wfw:commentRss><wfw:comment>http://blogs.msdn.com/bethmassi/rsscomments.aspx?PostID=9504586</wfw:comment><description>&lt;p&gt;I just posted an interview on Channel 9 on &lt;a href="http://channel9.msdn.com/posts/funkyonex/WPF-Improvements-in-Visual-Studio-2010-for-Building-Business-Apps/"&gt;&lt;strong&gt;WPF Improvements in Visual Studio 2010 for Building Business Apps&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt;.&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;At the MVP Summit a few weeks ago, Italian MVP &lt;a href="http://community.visual-basic.it/AlessandroEnglish"&gt;Alessandro del Sole&lt;/a&gt; was so excited about the new WPF features in Visual Studio 2010 that he asked me if he could interview &lt;a href="http://blogs.msdn.com/vbteam/archive/tags/Milind+Lele/default.aspx"&gt;Milind Lele&lt;/a&gt; himself to get the low-down -- I said sure! &lt;/p&gt;  &lt;p&gt;Milind is a Program Manager on the Visual Studio Pro Tools team. In this interview he chats with Alessandro about the new WPF improvements in Visual Studio 2010 for building business applications. This time Milind shows off the new Visual Studio UI and the new WPF data grid as he quickly builds a master-details form against an Entity Data Model using the new RAD drag-drop data binding features for WPF.&lt;/p&gt;  &lt;p&gt;Also check out Milind's &lt;a href="http://blogs.msdn.com/vbteam/archive/2008/11/19/drag-drop-data-binding-for-wpf-in-visual-studio-2010-milind-lele.aspx"&gt;blog post on this topic&lt;/a&gt; for more information. &lt;/p&gt;  &lt;p&gt;Enjoy!&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9504586" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/bethmassi/archive/tags/WPF/default.aspx">WPF</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Community/default.aspx">Community</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Videos/default.aspx">Videos</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Channel9/default.aspx">Channel9</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/Data/default.aspx">Data</category><category domain="http://blogs.msdn.com/bethmassi/archive/tags/VS2010/default.aspx">VS2010</category></item></channel></rss>