Quantcast
Channel: Windows Forms Data Controls and Databinding forum
Viewing all articles
Browse latest Browse all 2535

ADVANCE How to Delete selected row in data grid view and database by C# WITH Child References

$
0
0

Hello

I have read the below: 

How to Delete selected row in data grid view and database by C#

@

http://social.msdn.microsoft.com/Forums/en-US/650f8671-266d-4faa-9f23-3f0a81ed22f9/how-to-delete-selected-row-in-data-grid-view-and-database-by-c?forum=winformsdatacontrols

and I have followed the answer using and am now using a BindingSource for my DataGridView.

What I want :

I have 4 Datagridviews, one parent and 3 child. When I click a delete button and dlete a record in the parent, I expected any record in the child Datagridviews that is related to the parent to be automatically deleted as well.

Currently what happens is I use:

 foreach (DataGridViewRow item in ParentDataGridView.SelectedRows)
            {
               ParentGridView.Rows.RemoveAt(item.Index);
            }

The record disappear from the DataGridview but then I try to DBContext.SaveChanges(); I get the following error:

Additional information: The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

I did some research and found out that after I delete the Parent record, any child that use the Parent's PK as their FK will become orphaned and I can't tell EF to delete those Child Objects too. I've read about Identifying Relationships, I've read to use ObjectDelete instead of RemoveAt because  ObjectContext is better than DBContext (But I struggle to understand creating the ObjectContext, I also read that this isn't used for Code-First Approach). 

Steps that I have already taken:

Using DataAnnotations I have created Composite Keys, setting the 3 Child Table's PK to [Key, Column(Order = 2), and the FK linking to the Parent to [Key, ForeignKey("Parent"), Column(Order = 1)] (I don't know if that is enough to create the Identifying Relationships or is there more I need to do?)

I've also go to my SQL database and for each Table I set the ON DELETE to Cascade. 

I'm not sure how to get around this. Thanks!





Viewing all articles
Browse latest Browse all 2535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>