Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 5 - Deleting Child Records

VS 2012 (11.0.60315.01 Update 2), C# 5, Entity Framework 5.0.0.0 (Runtime v4.0.30319)

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. All I want to do is delete a record from the Child table. Can anyone help?

This is a full and simple example. The SaveChanges() throws the following exception:

"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."

The code looks like this:

using System.Linq;

namespace EFDeleteTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (EFTestEntities context = new EFTestEntities())
            {
                var parent = context.Parents.Single(p => p.Id == 1);

                var child = parent.Children.Single(c => c.Id == 1);

                parent.Children.Remove(child);

                context.SaveChanges(); // Throws the above Exception
            }
        }
    }
}

The Database looks like this:

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)

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.

like image 951
Rob L Avatar asked Jun 12 '13 03:06

Rob L


1 Answers

If all you want is to delete the child object, the parent object should not be concerned in the logic. Try the code below, let me know what happens (Not tested).

using System.Linq;

namespace EFDeleteTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (EFTestEntities context = new EFTestEntities())
            {                      
                var child = context.Children.Single(c => c.Id == 1);

                context.Children.Remove(child);

                context.SaveChanges();
            }
        }
    }
}
like image 157
Komengem Avatar answered Sep 29 '22 07:09

Komengem