Note that there are some explanatory texts on larger screens.

plurals
  1. POEntity Framework 5 - Deleting Child Records
    text
    copied!<p>VS 2012 (11.0.60315.01 Update 2), C# 5, Entity Framework 5.0.0.0 (Runtime v4.0.30319) </p> <p>I know similar questions have been posted in the past, but there does not seem to be an answer. I think I understand the error, but I'm more interested in finding the 'desired' solution. <strong>All I want to do is delete a record from the Child table.</strong> Can anyone help? </p> <p>This is a <strong>full</strong> and <strong>simple</strong> example. The <strong>SaveChanges()</strong> throws the following exception:</p> <p>"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."</p> <p>The code looks like this:</p> <pre><code>using System.Linq; namespace EFDeleteTest { class Program { static void Main(string[] args) { using (EFTestEntities context = new EFTestEntities()) { var parent = context.Parents.Single(p =&gt; p.Id == 1); var child = parent.Children.Single(c =&gt; c.Id == 1); parent.Children.Remove(child); context.SaveChanges(); // Throws the above Exception } } } } </code></pre> <p>The Database looks like this:</p> <pre><code>Parent Id (PK, int, not null) IDENTITY Name (nvarchar(50), null) Child Id (PK, int, not null) IDENTITY ParentId (FK, int, not null) -- Foreign Key to the Parent Table (Id column)) Name (nvarchar(50), null) </code></pre> <p>There is one record in the Parent table (Id = 1) and there are 2 records in the Child table (Id's 1 and 2). Both of the Child records have a ParentId = 1.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload