简体   繁体   中英

Deleting parent Entities without deleting related child

Hi I'm using Entity framework to set my database.I have one-many relation entity and I want to only delete parent entity without cascading deletion. I'm getting error from deleting from parents but I really want to keep my child as a recording reason. Is there any ways to delete only parents without an error?

This is an old question but I came across this problem today so I'll share the solution that I found.

The long-story-short version is that you need to eager load your child association. Assuming you have your relationships setup correctly and a Foo has many Bars , this code should do exactly what you want:

    public void Delete(Guid fooId)
    {
        using (var context = new MyDbContext())
        {
            var foo = context.Foos.Include("Bars").FirstOrDefault(foo => foo.Id == fooId);
            if (foo != null)
            {
                context.Foos.Remove(foo);
                context.SaveChanges();
            }
        }
    }

The key here is the call to .Include . Without this, the update will fail with a foreign key violation.

Now, when I say I assume you have your relationships setup right, I mean they should look like this.

// Foo.cs
public class Foo
{
    public Guid Id { get; set; }

    public ICollection<Bar> Bars { get; set; }
}

// Bar.cs
public class Bar
{
    public Guid Id { get; set; }

    public Guid? FooId { get; set; }

    public virtual Foo Foo { get; set; }
}

// MyDbContext
modelBuilder.Entity<Foo>()
    .HasMany(e => e.Bars)
    .WithRequired(e => e.Foo)
    .HasForeignKey(e => e.FooId)
    .WillCascadeOnDelete(false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM