Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7649079
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T10:52:28+00:00 2026-05-31T10:52:28+00:00

I’m trying to remove a child entity from a parent collection navigation property. There

  • 0

I’m trying to remove a child entity from a parent collection navigation property. There is a one-to-many relationship set up b/t parent and child. Once I remove the child, I want the database to remove the assoc. child record from the database rather than orphaning that record by nullifying the foreign key.

Is there any way to do this without having to explicitly delete the child via the child DbSet in the DBContext?

I’ve seen other posts related to this topic, but I thought I’d distill the code down to a simpler test case:

using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using NUnit.Framework;

namespace basic_tests
{
[TestFixture]
public class OneToManyTests
{
    #region Setup/Teardown

    [SetUp]
    public void SetUp()
    {
        _context = new Context();
        Database.SetInitializer(new DataInitializer());
    }

    #endregion

    private Context _context;

    [Test]
    public void CanRemoveChildThroughParent()
    {
        /**

        this throws : "System.Data.Entity.Infrastructure.DbUpdateException : An error occurred while saving entities that do not expose foreign key properties for              their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of               exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for                  
         details.System.Data.UpdateException : A relationship from the 'Child_MyParent' AssociationSet is in the 'Deleted' state. Given multiplicity constraints, a 
         corresponding 'Child_MyParent_Source' must also in the 'Deleted' state.

         **/

        var parent = _context.Parents.FirstOrDefault();
        var firstChild = parent.MyChildren.FirstOrDefault();
        parent.MyChildren.Remove(firstChild);

        _context.SaveChanges();

        var parentRefresh = new Context().Parents.FirstOrDefault();
        Assert.AreEqual(1, parentRefresh.MyChildren.Count);

        var childrenCount = new Context().Children.Count();
        Assert.AreEqual(1, childrenCount);
    }
}

public class Parent
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual ICollection<Child> MyChildren { get; set; }
}

public class Child
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual Parent MyParent { get; set; }
}

public class Context : DbContext
{
    public DbSet<Parent> Parents { get; set; }
    public DbSet<Child> Children { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Child>()
            .HasRequired(c => c.MyParent)
            .WithMany(p => p.MyChildren)
            .WillCascadeOnDelete(true);
    }
}

public class DataInitializer : DropCreateDatabaseAlways<Context>
{
    protected override void Seed(Context context)
    {
        for (var i = 0; i < 2; i++)
        {
            context.Children.Add(new Child
                                     {
                                         Name = "child" + i
                                     });
        }

        var parent = new Parent { Name = "parent", MyChildren = context.Children.Local.ToList() };

        context.Parents.Add(parent);

        base.Seed(context);
    }
}
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T10:52:29+00:00Added an answer on May 31, 2026 at 10:52 am

    Is there any way to do this without having to explicitly delete the
    child via the child DbSet in the DBContext?

    In your model: No, there is no other way. You have to call:

    var parent = _context.Parents.FirstOrDefault();
    var firstChild = parent.MyChildren.FirstOrDefault();
    _context.Children.Remove(firstChild);
    
    _context.SaveChanges();
    

    I recently have learned that there is one exception which causes an automatic delete in the database when you remove the child from the parent collection. That’s the so-called Identifying relationship which requires that the foreign key property in the child refering to the parent must be part of the (composite) primary key of the child:

    public class Child
    {
        [Key, Column(Order = 0)]
        public virtual int Id { get; set; }
        [Key, ForeignKey("MyParent"), Column(Order = 1)]
        public virtual int MyParentId { get; set; }
    
        public virtual string Name { get; set; }
        public virtual Parent MyParent { get; set; }
    }
    

    In this case your code would indeed delete the child from the database. It is explained here (last section at the bottom): http://msdn.microsoft.com/en-us/library/ee373856.aspx

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I am trying to render a haml file in a javascript response like so:
I am currently running into a problem where an element is coming back from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.