One-To-Many (Master-Detail) Forms with LINQ to SQL

Published 19 February 08 03:11 PM

In previous posts this month I showed how to use LINQ to SQL classes with a couple different Combobox data binding scenarios. (You can read those articles here and here.) Today I'm going to show you how to create a one-to-many data entry form (and we'll use a couple Combobox lookup lists as well). I'll show you what you need to do to enable proper insert, update and deletes of the hierarchical data. I'll also show how we can specify that these operations happen via stored procedures.

The Database Model

For this example I'll be creating my own database and not using Northwind. This is because Northwind isn't a very typical database especially when it comes to referential integrity. I want to create tables that have non-nullable foreign keys as well as use a timestamp field for concurrency checking.

So here's the database diagram of what we'll be building off of:

I've also specified Update, Insert and Delete stored procedures for each of the tables. This is so we can lock down the database security a bit and disallow UPDATE, INSERT and DELETE SQL statements from executing against it. All we need to grant is SELECT and EXECUTE permissions. This is a typical configuration for databases because it helps prevent against malicious code executing on the database by stopping changes from happening outside the stored procs.

So to get started building my form, I'll start by adding a new item to my project called "LINQ to SQL Classes" which will open the O/R designer and allow me to drag tables in my database from the Server Explorer onto the model's design surface. I'll drag all of the four tables above and since the database is called OMS I'll name the model OMS.dbml. This will create our LINQ to SQL classes and infer the associations from the database relationships. I'll also drag all the stored procs onto the Methods pane.

Next we want to associate the stored procs with the update, insert and delete behaviors for each class. Select the class then in the properties window you will see three properties; Delete, Insert and Update and they are all set to "Use Runtime". Select the properties and you then can specify the procedures in the methods pane to use for each behavior. You can also simply right-click on the class and select "Configure Behavior". On this screen you can specify the behavior for all the classes by selecting the Customize radio button and then selecting the corresponding procedure shown in the method pane.

After you got all of these set up, save the model and this will generate all the LINQ to SQL classes plus the DataContext which is used to manage the connection and communication to our database.

Data Sources and Data Binding the Form

Next we need to get these into our Data Sources window so that we can quickly get our form designed. I showed how to do this before in the previous posts against Northwind. This time I want to create a master-detail form of Orders and related OrderDetails in a grid and I want to show the Customer and Product as lookup lists. Select Add New DataSource from the Data menu and select Object as the Data Source Type. Next, select the Order class and click Finish. This will populate your Data Sources window with the Order and also its related OrderDetails because of the association. We'll also want to add Customer then Product to our Data Sources window as well because we'll need those for our lookup lists.

When you inspect the properties of the classes in the Data Sources window you will see that the associated parent object is also visible along with the child collections. For instance, if you expand Order you will see the parent Customer as well as the child OrderDetails. This indicates the associated parent Customer object for that Order object. I'm going to want to display that information as a lookup list so change the drop control for Customer to "None" and change the CustomerID to a Combobox. I also do not want to display the Modified field so also set that to "None". Then I'll set the drop control of the Order to "Details".

Drag the Order onto the form to set up the controls as well as the BindingNavigator and BindingSource for the Order. Next drag the Customer from the Data Sources Window onto the top of the CustomerID Combobox to set up the CustomerDataSource for the list of items. In the properties for the Combobox set the ValueMember = CustomerID and the DisplayMember = LastName in order to finish setting up the lookup list for Customer.

Next drag the OrderDetails listed under Order onto the form to drop down a DataGridView. You will notice that this will also pull in the parent objects, Product and Order in this case. Just edit the columns and remove those as well as the Modified field. For this example, I'll still display but set the OrderDetailID and OrderID to ReadOnly since these will be filled in automatically for us after we save the data. We'll also need to change the ProductID column type to a DataGridViewComboBoxColumn and then select the Product as the DataSource by selecting Other Data Sources --> Project Data Sources --> Product. This process will create a ProductBindingSource in the component tray.

Also we will need to specify the DisplayMember = Name and ValueMember = ProductID on the column here.

Loading the LINQ to SQL Classes with Data

Now that we have our form designed and the data binding all set up we're ready to create our objects and fill them with data. Unlike when we are using DataSets on our forms, the Form Designer will not generate any loading or saving code for us when using LINQ to SQL classes. But the code we need to write is very straightforward and we can write LINQ queries to limit our result sets. For this simple example I will select all Orders and also all of the Customers and Products into our lookup lists but keep in mind this may be a bad design if there are hundreds of rows in your database. In that situation it's better to write a search form.

So in the Form's Load event handler we need to set up the BindingSource's DataSources with data returned from our tables. First we'll fill the form with all the orders from the Orders table.

Public Class Form1

    Dim db As New OMSDataContext

    Private Sub Form1_Load() Handles MyBase.Load

        Me.OrderBindingSource.DataSource = db.Orders

Next we want to populate the Customers list. We can get cute and can specify a LINQ query here in order to select the customer names in "LastName, FirstName" format.

        Me.CustomerBindingSource.DataSource = From c In db.Customers _
                                              Let LastName = c.LastName & ", " & c.FirstName _
                                              Select LastName, c.CustomerID _
                                              Order By LastName

Finally we want to select our list of Products. Here's a trick that will place an "empty" product at the top of the list so that it can indicate to the user to select a value. We can add validation later to check that the selection has been made by checking that the ProductID > 0.

        Dim emptyProduct As Product() = _
                {New Product With {.Name = "<Select a product>", .ProductID = 0}}

        Me.ProductBindingSource.DataSource = (From Empty In emptyProduct).Union( _
                                              From Product In db.Products _
                                              Order By Product.Name)

    End Sub

You might be wondering why we're not explicitly setting the OrderDetailBindingSource's DataSource. This is because the OrderDetails are loaded from the database automatically only when we access the OrderDetails collection on the Order object. This happens when the OrderBindingSource moves position and the OrderDetailsBindingSource needs to display the OrderDetail objects for the Order. If you want to see the T-SQL statements being run just put a call to db.Log = Console.Out in the Load to display the statements in the Debug Output window. Just make sure to remove it before building your release.

Saving Hierarchical Data

Next we need to add the save code by enabling the save button and handling the click event. In my previous post when we built a single-table entry form with a lookup list I showed how to do this:

    Private Sub OrderBindingNavigatorSaveItem_Click() _
        Handles OrderBindingNavigatorSaveItem.Click

        Me.Validate()
        Me.OrderBindingSource.EndEdit()
        Me.OrderDetailsBindingSource.EndEdit()

        Try
            db.SubmitChanges()

            MsgBox("Your data was saved.")

        Catch ex As Exception
           MsgBox(ex.ToString)
        End Try

    End Sub

Okay so let's give this form a try. Run the form and make a change, and/or insert a new Order, click save, and you should see that everything worked out smoothly. The keys are properly populated on insert and the relationship works correctly. However if we try to delete an OrderDetail (child) row from our grid we get the following error:

System.InvalidOperationException: An attempt was made to remove a relationship between a Order and a OrderDetail. However, one of the relationship's foreign keys (OrderDetail.OrderID) cannot be set to null.

To fix this we need to indicate to the model that we want to delete the OrderDetail when it's OrderID is set to null. Unfortunately this cannot be done in the O/R designer so you have to open the model in an XML editor. Fortunately, once you change it the designer won't mess with it again unless you remove the class completely. Open the dbml file with the XML Editor (just right-click on it an select "Open with...") and locate the XML that describes the OrderDetail class. Notice the association under the OrderDetail table:

<Table Name="dbo.OrderDetail" Member="OrderDetails">
  <Type Name="OrderDetail">
    <Column Name="OrderDetailID" Type="System.Int32" DbType="Int NOT NULL IDENTITY" 
IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" /> <Column Name="OrderID" Type="System.Int32" DbType="Int NOT NULL" CanBeNull="false" /> <Column Name="ProductID" Type="System.Int32" DbType="Int NOT NULL" CanBeNull="false" /> <Column Name="Quantity" Type="System.Int32" DbType="Int NOT NULL" CanBeNull="false" /> <Column Name="Price" Type="System.Decimal" DbType="Money" CanBeNull="true" /> <Column Name="Modified" Type="System.Data.Linq.Binary" DbType="rowversion NOT NULL"
CanBeNull="false" IsVersion="true" /> <Association Name="Order_OrderDetail" Member="Order" ThisKey="OrderID"
Type="Order" IsForeignKey="true"/>
<Association Name="Product_OrderDetail" Member="Product" ThisKey="ProductID"
Type="Product" IsForeignKey="true" /> </Type>

We need to add an attribute here called DeleteOnNull and set it to true in order to be able to delete a child row independently in the database when calling SubmitChanges(). Once we make this change we can now delete just a single OrderDetail from the grid and save normally:

<Association Name="Order_OrderDetail" Member="Order" ThisKey="OrderID" Type="Order" 
IsForeignKey="true" DeleteOnNull="true"/>

The other option to fix this issue is to modify the Delete Rule to "Cascade" on the relationship in the database. In that case the designer correctly infers this attribute on the association.

Okay let's run the form again and now when you try to delete an OrderDetail child from the grid and click save, it saves without error. But if you try to delete an entire order by clicking the delete button on the ToolStrip and then save we now get a database error:

System.Data.SqlClient.SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_OrderDetail_Orders". The conflict occurred in database "OMS", table "dbo.OrderDetail", column 'OrderID'.
The statement has been terminated.

This is because unlike DataSets, you can't specify in the model that when you delete a parent, it should cascade to the children automatically. So we need to write some code to do this. There's a variety of ways you can do this and one way I already showed in a previous post by adding code to the DataContext that works nicely if we are not using stored procs. The basic idea is that we need to tell the DataContext to delete the child objects anytime an Order is deleted. In this example, I chose to do this by calling DeleteOnSubmit before we call SubmitChanges. I added this code into the Click event handler for the Delete button on the ToolStrip of the form:

    Private Sub BindingNavigatorDeleteItem_Click() _
        Handles BindingNavigatorDeleteItem.Click

        If Me.OrderBindingSource.Position > -1 Then
'Grab a reference to the currently selected order
Dim order As Order = CType(Me.OrderBindingSource.Current, Order)
'Ensure that children are deleted when the parent is deleted For Each detail In order.OrderDetails db.OrderDetails.DeleteOnSubmit(detail) Next End If End Sub

Now run the form and try a variety of Update, Insert and Delete operations on the data and you will have a smooth ride. If you enable logging on the DataContext or run SQL profiler on the database you will see our stored procedures being called in the proper order.

Next time I'll show you how we can add simple validation to our LINQ to SQL classes by creating a base business class to inherit from and using the IDataErrorInfo interface along with the ErrorProvider.

UPDATE: I placed the code for this article (including the previous article code on this topic) into a Code Gallery project for you to play with.

Enjoy!

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# DotNetKicks.com said on February 19, 2008 6:23 PM:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# burrowsuw said on February 19, 2008 9:26 PM:

Hi Beth,

WhenI was teaching, I had a student who came to my office to tell me that I used the word "irregardless". She let me know that since I was a professor, I should know better and use the proper word, i.e., regardless.

I learned the original word from listening to my mom, who uses irregardless to this day.

Anyway, I thought I would be a pedant and let you know that the test in your message box that says "Your data was saved." is incorrect (sorry, I ma just getting back at that student). The word "data" is plural, so you should say "Your data were saved."

How about that for a useless and dumb comment :)

bill

# Allan said on February 19, 2008 10:34 PM:

Data leads a life of its own quite independent of datum, of which it was originally the plural. It occurs in two constructions: as a plural noun (like earnings), taking a plural verb and plural modifiers (as these, many, a few) but not cardinal numbers, and serving as a referent for plural pronouns (as they, them); and as an abstract mass noun (like information), taking a singular verb and singular modifiers (as this, much, little), and being referred to by a singular pronoun (it). Both constructions are standard. The plural construction is more common in print, evidently because the house style of several publishers mandates it.  

In the case of messages from within this context (a master/detail form) the singular modifier is infered as we are saving a single record even though it may have many associated child records.

I couldn't leave that post unaswered, sorry!

# Allan said on February 19, 2008 10:36 PM:

Great post by the way.  It answers quite a few questions I have had.  On a slightly different path, is there a way we can determine the templates the generated code uses?

Thanks in advance.

# karl1406 said on February 20, 2008 6:05 AM:

Beth,

Love your work!  Thanks for sharing with us.

Karl

# Hernan said on February 20, 2008 6:52 AM:

Hi Beth!

Your blog and videos are amazing and really usefull!

This is my first comment, or let me say my first question : Did you test this master-detail scenario using uniqueidentifiers as keys?

Is not binding the databinidingsource of the details table when I navigate the master table...

Thanks.

# Josh Stodola said on February 20, 2008 10:34 AM:

Beth,

Thanks for posting this.  I definitely learned a few things from it.  Keep up the great work!

LMAO @ bill's comment.  I think if she put that sentence in the message box, more people would  comment to say "You have a typo in your message box".  And LMAO even harder at Allan's response to bill (at least the percentage of the response that I was able to comprehend).

# Peter Kellner said on February 20, 2008 10:48 AM:

Nice!  good to have it spelled out so cleanly.

# Beth Massi said on February 20, 2008 12:10 PM:

Hi Allan,

You can't change the templates the designer uses. You'd have to write your own code generator.

-B

# Beth Massi said on February 20, 2008 12:14 PM:

Hi Hernan,

Yes this will work with uniqueidentifiers. Actually, it's even easier than DataSets in this case because you can set in the model the class's guid property to "Auto Generated Value" = True and Auto-Sync = OnInsert and then just specify the default on the database column to (newid()) and it will handle it all for you. I suspect something is wrong with the BindingSources. Make sure that the child's BindingSource's DataSource property is set to the parent's BindingSource.

HTH,

-B

# Allann said on February 24, 2008 11:13 PM:

Hi Beth,

I found out that edmx files use the SingleFilegenerator "Custom Tool" to generate the code behind files as do other "wizards", so it's just a matter of writing your own to output your own code behind.  Is this what you meant when you said "write your own code generator"?

Thanks

Allan

# Chris Rock said on February 25, 2008 1:54 PM:

Beth,

I'm compiling a list of articles, tutorial and opinions about LINQ TO SQL. I hope you don't mind but I added a few of your links to the list.

Chris

# Beth Massi - Sharing the goodness that is VB said on February 25, 2008 8:04 PM:

In the last few posts on LINQ to SQL I've showed how to set up an object model using the O/R designer

# Noticias externas said on February 25, 2008 8:29 PM:

In the last few posts on LINQ to SQL I&#39;ve showed how to set up an object model using the O/R designer

# Beth Massi said on February 25, 2008 10:17 PM:

Hi Alan,

Yep. Here's an example that may interest you: http://code.msdn.microsoft.com/sampleedmxcodegen

HTH,

-B

# Beth Massi said on February 25, 2008 10:18 PM:

Hi Chris,

I don't mind at all. You may also want to check out Code Gallery for LINQ to SQL samples: http://code.msdn.microsoft.com/Project/ProjectDirectory.aspx?TagName=LINQ%20to%20SQL

HTH,

-B

# Chris Rock said on February 26, 2008 2:43 PM:

Beth,

Thank you for that link!

Chris

# James said on February 29, 2008 3:26 PM:

Hi Beth

I saw your sub

Private Sub BindingNavigatorDeleteItem_Click() _

But if I want to display a error message to the user and retrieve the info, how I can do that?

Thanks you for your help

James

# Rikki said on March 2, 2008 5:05 PM:

Hi Beth,

I'm not sure this is the right place to ask this, but since I've searched high and low, I'll give it go anyway.

I'm trying to update a row in a datagrid, much like you describe above, which contains several dropdownlists. One of them has a foreignkey to my table 'tblCapacity' whit null values allowed. When I try to edit a row where a null value is currently in the capacityID attribute I get the message:''CapacityDropDownList' has a SelectedValue which is invalid because it does not exist in the list of items.

Parameter name: value'

I've tried (a mix from your code above and Scott Guthrie's in LINQ to SQL Part 9) to change the selectstatement of the linqdatasource I use for the dropdownlist like so:

   Protected Sub CapacityLinqDataSource_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.LinqDataSourceSelectEventArgs) Handles CapacityLinqDataSource.Selecting

       Dim campaignXL As New CampaignXLDataClassesDataContext

       Dim iNullable As Nullable(Of Integer)

       Dim emptyCapacity As tblCapacity() = _

               {New tblCapacity With {.capacityCode = "<Select a capacity>", .capacityID = iNullable}}

       Dim capacity = (From Empty In emptyCapacity).Union( _

                                             From tblCapacity In campaignXL.tblCapacities _

                                             Order By tblCapacity.capacityCode)

       e.Result = capacity

   End Sub

This doesn't work (when I edit the row it gives an error saying iNullable should have a value); when I assign '0' to iNullable it gives me the earlier error message (for a good reason because the null value is still not present in the linqdataset for the dropdownlist.

It seems to work if I make a dynamicdata project out of my datamodel, so somehow there is a solutions for this problem. Hope you can help my, thanks in advance,

Rikki

# Grzegorz said on March 7, 2008 5:31 AM:

Great text! Very helpfull.

Now I see DataSet is dead - the end of database concept. Welcome to business objects concept.

Thats a pitty that O/R designer cannot set the association properties and one has to do it in xml. I think maybe service pack 1 for VS 2008...

# Fatih said on March 13, 2008 5:37 PM:

Hi, been learning from you for a few weeks now, much respect.

I get an error with your program when i do something i will guide below, after which everything fails (need to restart program).

1: on a new orderdetail fill in only quantity and price, leave combobox as is.

2: Try to save. You'll get a warning.

3: Now highlight this orderdetail we worked on and delete..

4: Now save again and you get an error about relation violation. After this you cant work with the database anymore.

Can you Beth or anyone else tell how to fix this? I think this will happen with everyone.

Thanks great tutes xx

# Beth Massi - Sharing the goodness that is VB said on April 12, 2008 12:27 PM:

In my previous posts on LINQ to SQL I showed how to build LINQ to SQL classes and set up the data binding

# Beth Massi - Sharing the goodness that is VB said on April 14, 2008 2:08 PM:

In my last post we built the service and data access layer for our LINQ to SQL N-Tier application. In

# Simone said on April 18, 2008 1:04 PM:

Hi Beth. Great articles!!!

I have a question, I read your articles about smart client with Linq. I have to implement a connected client with Linq. My problem is he following:

Suppose I mapped with Linq tables Orders, OrderDetails and OrderDetailLines. An order has many OrderDetails and each OrderDetail has many detailLines. I created a formOrder where I Have a datacontext and I retrieve info about an order and I show a grid with orderDetails. All is databound. If I doubleclick on a detail row I show another form: OrderDetailForm (I pass to the form the rowDataboundItem) where I show OrderDetail and a grid with OrderDetailLines. I want to implement an UNDO feature, so if I modify an OrderDetailLine and then I press "Cancel Button" the orderdetailLine object is not modified. The same is for the orderdetail. I tried to implement IEditableObject but I have problems with relations properties (they return empty). I can't get "GetOriginalEntityState" methods because I must have the ability of edit a child object, then press ok to update it, the re-edit and press "Cancel" (and I want last updated values, not db values).

I'ts a very frustrating problem from me...It's five days I try every kind of solutions...!

The problem is that with databinding values are automatically updated. I could clone objects but I have a large number of business objects and implement a clone method would mean too many days.

Any idea??

Thank's in advance and sorry for the english...!

# Brian in England said on May 2, 2008 4:46 AM:

Please can you put all this new programming in to new video, as an add on the ‘Use DataSets in an N-Tier Application’ as I find it hard to follow.

# Gonzalo said on May 7, 2008 8:56 PM:

Hi Beth,

Awesome topics. Thanks for being such a soothing breeze in the "Sea of Linq". Would you suggest a way to handle Default Values With LINQ to SQL. I would like to be able to use my default values previously set on my SQL database with Linq when I do an insert to a table for data entry.

Best regards,

Gonzalo

# Burton Roberts said on May 15, 2008 12:42 PM:

The OMS_log.ldf file seems to be missing on the download.  I can't seem to attach OMS without it.

Thanks

Your work is great.

# Burton Roberts said on May 16, 2008 4:37 PM:

Okay, I built the OMS from scratch in SQLExpress. I just installed SQL 2008 Feb CTP, moved it, and upgraded to VS2008 SP1 (beta) and Framework 3.5 SP1  I'm not getting the OrderDetails collection represented within the "Order" Class in Data Sources window after I drag the Order table onto it. However I am getting "Orders" (not "Order") under Customer.

BTW the table is "Orders" in the database and magically becomes "Order" in the OMS.dbml.  Why, and could this be an issue. I then changed the name to "Orders", rebuilding and still getting no representation of the OrderDetails collection.

# George Gopie said on May 19, 2008 2:11 PM:

Hi Beth,

I am building a small application with Master Detail forms. iave the DB design with necessary Primary Keys and FK's. I have combo boxes on some columns in the Detail forms. I am unablke to update or save new data from the DEtail forms.

Can you Please advise.

# Beth Massi said on May 19, 2008 4:55 PM:

Hi Burton,

When you attempt to attach the mdf file just remove the LDF reference and click OK. SQL-Server will rebuild it. You can also run the sample as it is packaged as a user instance.

I'm not sure of the SP1 beta behavior but in the released version as long as you have referential integrity set up on your tables and you drag both of them onto the LINQ to SQL O/R designer, it will infer the relationships. The designer will rename your classes to singular but the child collections on the class are plural properties. This is just the default, you can change it.

HTH,

-B

# Beth Massi said on May 19, 2008 4:57 PM:

Hi George,

Does the sample provided with this post work for you? Check the update statements and make sure you are calling EndEdit on the binding sources before attempting to save.

-B

# Gonzalo Chiriboga said on May 27, 2008 1:07 AM:

Hi Beth,

Thanks in advance! Would you suggest a way to handle Default Values With LINQ to SQL. I would like to be able to use my default values previously set on my SQL database with Linq when I do an insert to a table for data entry.

Apologies for insisting on this question.

Warm regards,

G

# Beth Massi said on May 27, 2008 3:36 PM:

Hi Gonzalo,

If you want the defaults to appear on the objects when you add them to the collections you can do this in a variety of ways. You can take a look at the OnCreated partial method to set values when the object is created. But since LINQ to SQL classes are just plain CLR classes you could also just create a non-default constructor and pass it any values you want:

Sub New(ByVal orderDate As Date)

   Me.New()

   'Set default values

   Me._OrderDate = orderDate

   Me._CustomerID = 1

End Sub

Then on your form you could handle the BindingSource.AddingNew event:

Private Sub OrderBindingSource_AddingNew(ByVal sender As Object, ByVal e As System.ComponentModel.AddingNewEventArgs) Handles OrderBindingSource.AddingNew

   Dim o As New Order(Date.Today)

   e.NewObject = o

End Sub

HTH,

-B

# Gonzalo Chiriboga said on May 28, 2008 1:27 PM:

Thanks a lot Beth! You are a VB angel.

TH,

G

# Dating said on May 31, 2008 1:47 PM:

In previous posts this month I showed how to use LINQ to SQL classes with a couple different Combobox data binding scenarios. (You can read those articles here and here .) Today I'm going to show you how to create a one-to-many data entry form (and we'l

# Weddings said on June 5, 2008 7:43 AM:

In previous posts this month I showed how to use LINQ to SQL classes with a couple different Combobox data binding scenarios. (You can read those articles here and here .) Today I'm going to show you how to create a one-to-many data entry form (and we'l

# pgraves said on June 11, 2008 5:26 PM:

Thanks Beth, Being quite new to Linq I have been grateful for your videos and other help in getting my master details forms working properly.  However there is one scenario below in which I am still struggling to get my data to update efficiently.

I have a form in which the controls on the top half are bound to fields in a table (Vehicles) using LINQ, and the bottom half shows a datagrid with rows from a related table (Vehicle Status).

A few of the controls in the top half display data from a view which is bound to the Vehicles, and which only shows the most recent records from Vehicle Status - giving information about the current (most recent) status.

When the vehicle status changes I successfully insert a new row in the vehicle status table, using the sequence: bindingsource.endedit, BindingSource.Add, datacontext.submitchanges, and the new record is saved as the most recent item in the status table.  The datagridview refreshes and shows the new data row at the top as expected.

However the controls in the upper portion of the form which are bound to the 'latest status' view do not refresh to show the new latest status data.

I am now calling BindingSource.ResetBindings(False) on the vehicles table and the status table as well as calling datacontext.Refresh(Data.Linq.RefreshMode.OverwriteCurrentValues, VehicleBindingSource), all to no avail.  Even requerying the data from the database does not refresh the controls on the form.  The only way I can refresh this data is by closing and re-loading the form - not the most elegant solution.

This is now a large application so posting code will be a major operation, however any ideas would be very much appreciated.

Regards,

Pete

# Kim said on July 2, 2008 7:58 AM:

Hi Beth

Your articles are Great !!!

Quick Question

How do delete an individual row from the orderdetails datagridview ?

Also how can I prevent the user from entering alpha data in a numeric field in the datagridview ?

# Beth Massi said on July 21, 2008 4:14 PM:

Hi Kim,

You call the OrderDetailBindingSource.Remove method to delete the current row. The DataGridView will also delete a row if you select the row header on the left and then press the delete key.

Check out this topic (and related resources at the bottom) for info on formatting data in the DataGridView: http://msdn.microsoft.com/en-us/library/hezscd0d.aspx

HTH,

-B

# JMSteele said on August 2, 2008 8:34 AM:

Beth, thanks for all your efforts. I'm a big fan.

I've hesitated bothering you with this recurring problem but it's vexed me no matter how many times I've followed this tutorial either here or in the HDI vid version.

Most of the time, though not all, the following IndexOutOfRangeException is rasied when I close the form:

"Index 0 does not have a value at System.Windows.Forms.CurrencyManager.get_Item(Int32 index) at

System.Windows.Forms.DataGridView.DataGridViewDataConnection.GetError(Int32rowIndex)."

I'm using VB 2008 Professional on a 64-bit unit, with a target platform of x86. Googling around has failed to help. Perhaps you can point me in the right direction? Please.

Best wishes,

Jim

# JMSteele said on August 2, 2008 9:17 AM:

Followup: I've managed to stop the error by  adding this to the FromClosing event:

Me.OrderDetailsDataGridView.Refresh()

I still have no clue as what initially caused the aforementioned error, however. Oh, well. It's working now, anyway.

Take care,

Jim

# JMSteele said on August 3, 2008 1:13 AM:

Okay, now I'm being a nudge, but ...

Can someone please clear this up for me?: I was given to understand that the LinqToSql class dbml is for one to one relationships only. If one wants to work with one to many relationships,  SqlMetal generated class files is the way to go, so the advice goes.

What am I not understanding properly? Orders to Order Details, as we have in this tutorial, is a one to many relationship, is it not?

# Beth Massi said on August 4, 2008 11:46 AM:

Hi JMSteele,

You can definately represent one-to-many relationships with LINQ to SQL. LINQ to SQL classes are representations of the tables in your database and so the MAPPING is one class = one table. These classes use the database relations to create the one-to-many associations.

However it is very common in non-trivial applications for the need to map your calsses to multiple underlying tables in the database and that is something that Entity Framework does (which will be released as part of Visual Studio SP1 this summer).

HTH,

-Beth

# JMSteele said on August 5, 2008 1:29 AM:

Much thanks for the clear response, Beth. Now it makes sense.

# Tom said on August 9, 2008 11:03 PM:

Hi

First sry for my bad English. You'r tutorials are very good and i learn so much so tnx a lot. I have just one question. How is possible "price" to be in "product" table and when you choose a product you get price to for this product . Then you just put a Quantity and you get total automatically :).

Tnx for any help and ty for all your tutorials they are best.

Bye

# John said on August 29, 2008 8:39 AM:

I have the exact same problem that Fatih has.

Any ideas how to solve it?

I spend a few hours but found no way to overcome this one!

I quote Fatih:

": on a new orderdetail fill in only quantity and price, leave combobox as is.

2: Try to save. You'll get a warning.

3: Now highlight this orderdetail we worked on and delete..

4: Now save again and you get an error about relation violation. After this you cant work with the database anymore."

# Russ said on September 9, 2008 7:46 PM:

I spent most of my day working on this issue - finding this article was a life saver.  Thank you for your expertise.  

So do you forsee Microsoft adding the ability to specify the ondelete behavior through the user interface in the future?

# Benoit said on September 10, 2008 1:26 PM:

To : pgraves or people who have the same problem

I got this same problem for a similar project.. the way i resolve it.. is, i dispose the Datacontext object and recreate an instance of it..

To : Beth

Very good work...! i like every screencast you made!

Thanks!

# Emmanuel Nuyttens said on October 14, 2008 4:20 AM:

Hi Beth,

I have a problem with de "Delete" of OrderDetails in the DeleteItem_Click. In my C# code (sorry, i'm not realy into VB.NET), when I click the "Delete" button in the navig. bar, I get the previous order when i check on the currentitem so :

Order order = (Order)this.orderBindingSource.Current;

doesn't give me the "deleted" order but the previous one. Then i checked you're VB.NET example and here i got the right (deleted one).

I hade to change my C# Code as next to make it work:

private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)

       {

           //The basic idea is that we need to tell the DataContext to delete the child objects anytime an Order is deleted.

           //In this example, I chose to do this by calling DeleteOnSubmit before we call SubmitChanges.

           //I added this code into the Click event handler for the Delete button on the ToolStrip of the form:

           try

           {

               this.Cursor = Cursors.WaitCursor;

               // Get the changed Objects

               ChangeSet changeSet = _db.GetChangeSet();

               if (changeSet.Deletes.Count > 0)

               {

                   // Check the deleted ones

                   foreach (var deletedOrder in changeSet.Deletes)

                   {

                       // Check first if deleted object is of "Order" type

                       if (deletedOrder.GetType().Name == "Order")

                       {

                           Order currentOrder = (deletedOrder as Order);

                           if (currentOrder != null)

                           {

                               // Mark related OrderDetail records for deletion.

                               foreach (OrderDetail detail in currentOrder.OrderDetails)

                               {

                                   _db.OrderDetails.DeleteOnSubmit(detail);

                               }

                           }

                       }

                   }

               }

           }

           catch (Exception ex)

           {

               MessageBox.Show(ex.Message);

           }

           finally

           {

               this.Cursor = Cursors.Default;

           }

       }

   }

Any clue ?

greetz,

Emmanuel Nuyttens.

# Beth Massi said on October 17, 2008 7:58 PM:

Hi Emmanuel ,

In your situation you may need full control over the order things are deleted. You can solve this very easily. In the form designer select the OrderBindingNavigator and for the DeleteItem property set that to "(none)". Now we can write the delete manually on the Order and the OrderDetails in the Click event handler. It's the same code as before, but at the end we need to delete the parent order:

Private Sub BindingNavigatorDeleteItem_Click() _

      Handles BindingNavigatorDeleteItem.Click

       If Me.OrderBindingSource.Position > -1 Then

           Dim order As Order = CType(Me.OrderBindingSource.Current, Order)

           'Ensure that children are deleted when the parent is deleted

           For Each detail In order.OrderDetails

               db.OrderDetails.DeleteOnSubmit(detail)

           Next

           '******

           Me.OrderBindingSource.Remove(order)

           '******

       End If

   End Sub

HTH,

-B

# Emmanuel Nuyttens said on October 22, 2008 4:26 AM:

Hi Beth,

Allright, this works smoothly, thx for the quick reply !

Emmanuel.

# peter sha said on October 22, 2008 6:29 AM:

Hi Beth,

Thanks for such great post, it's really helped us to resolve relationship problems we're having in O/R designer.

Still, we're stuck at the following problem:

Suppose we have a two level dataGrid (we're using UltraGrid in our project), if while saving a newly added row at the second (child) level, an error occurs from the database (unique key constraint, for example,) and we delete the newly added row (that caused the trouble) and submit the changes again, it throws an error "Unabled to remove a relationship ..."

However, we can reinitialize the database to get rid off with the error but doing so will detached the Grid from datacontext and any other changes will also be lost.

It appears to be a bug in Change Tracker not been resolved in SP1 as well since, if we add and immediately delete a new row without calling submit changes in between, everything works fine.

Thanks

# Beth Massi said on October 22, 2008 11:59 AM:

Hi Peter,

It sounds like the relationship isn't being picked up between parent/child on the client side. Can you make sure your bindingsources are configured properly? Does it work if you use two DataGridViews with bindingsources as I'm doing in this example?

You may also want to ask your question to the LINQ to SQL forums: http://forums.microsoft.com/MSDN/ShowForum.aspx?ForumID=2035&SiteID=1

HTH,

-B

# peter sha said on October 23, 2008 7:42 AM:

Hi Beth,

Thanks for the reply. The problem has somewhat been caught.

Actually, we're using parent.child.add(NewRow) procedure since using InsertOnSubmit makes UltraGrid lost one of many newly added rows while it still exists in the data context causing database to fire any  validation error infinitely. It seems the Add method creates a child entity only and does not attach it explicitly with data context till submit changes is called.

Similarly, we're using parent.child.remove(SelectedRow) (since DeleteOnSubmit works only with attached records), which works fine, but if some error occurs while submitting a new record and we remove  that row and call submit changes, relationship error occured.

Now the solution: I've added extra InsertOnSubmit statement (that would attach added row with data context) along with parent.child.add and have replaced parent.child.remove with DeleteOnSubmit and it's been working fine.

Thanks for that link, it would definitely be helpful.

# George said on December 12, 2008 9:42 PM:

Hello Beth and thank you for your videos.

Unfortunately, being visually impaired, they are

a bit difficult to see.

I am interested in creating a database application.

My question to you is, do you know of any text that

gives step by step instructions on how to use this new

LINQ to add, edit, update, delete and search?

I'm interested in the add, edit, update and delete

being on the form with the search button being able

to open another form with a grid. There, the user

can select the record they want and have the first

form populated with the information for editing.

Thank you very very very very very much in advance.

--George

# Beth Massi said on December 15, 2008 1:19 PM:

Hi George,

There are a lot of good articles on this blog as well as ThinqLinq.com. I'd also read through the walkthroughs in the MSDN Documentation: http://msdn.microsoft.com/en-us/library/bb399349.aspx

HTH,

-B

# Sunil K said on March 11, 2009 2:41 AM:

I have a form containing two DataGridView Controls.  DataGridView1 & DataGridView2.

Northwind Database used.

//Code

BindingSource OrdBindingSource = new BindingSource(NorthwindDataSet, "Orders");

//"OrderToOrderDetailsRelation" is Parent Child Relationship between Orders & OrderDetails Table filled in the Northwind DataSet.

BindingSource OrdDetailsBindingSource = new BindingSource(OrdBindingSource, "OrderToOrderDetailsRelation");

DataGridView1.DataSource = OrdBindingSource;

DataGridView2.DataSource=OrdDetailsBindingSource;

how do i sum Column Values of Expression Column (Total Value) of DataGridView2.

I want to reflect the sum into a textbox whenever I select different rown in DataGridView1.

# Sunil K said on March 11, 2009 2:52 AM:

in addition I am using Untyped DataSet.

I have learned from your VB.NET video on How Do I: Video Series.

the Code Provided with the video is:

Private Sub CategoriesBindingSource_CurrentChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CategoriesBindingSource.CurrentChanged

       Dim row As CategoryProductDataSet.CategoriesRow

       row = CType(CType(Me.CategoriesBindingSource.Current, DataRowView).Row, CategoryProductDataSet.CategoriesRow)

       Dim total = Aggregate Products In Me.CategoryProductDataSet.Products _

                   Where Products.CategoryID = row.CategoryID AndAlso _

                   Products.Discontinued = False _

                   Into Sum(Products.UnitPrice * Products.UnitsInStock)

       Me.TextBox1.Text = Format(total, "c")

   End Sub

I just Want to know, how do i implement this in my C# Code.

# Beth Massi said on March 11, 2009 2:44 PM:

Hi Sunil,

The Aggregate keyword is VB-specific and isn't supported in C#. Instead you have to call the .Sum extension method and pass it a lambda expression. This should help you get started:

http://msdn.microsoft.com/en-us/vcsharp/aa336747.aspx

HTH,

-B

Leave a Comment

(required) 
(optional)
(required) 

About Beth Massi

Beth is a Program Manager on the Visual Studio Community Team at Microsoft and is responsible for producing and managing content for business application developers, driving community features and team participation onto MSDN Developer Centers (http://msdn.com), and helping make Visual Studio one of the best developer tools in the world. She also produces regular content on her blog (http://blogs.msdn.com/bethmassi), Channel 9, and a variety of other developer sites and magazines. As a community champion and a long-time member of the Microsoft developer community she also helps with the San Francisco East Bay .NET user group and is a frequent speaker at various software development events. Before Microsoft, she was a Senior Architect at a health care software product company and a Microsoft Solutions Architect MVP. Over the last decade she has worked on distributed applications and frameworks, web and Windows-based applications using Microsoft development tools in a variety of businesses. She loves teaching, hiking, mountain biking, and driving really fast.
Page view tracker