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?
Asked
Active
Viewed 1,607 times
2
-
See http://stackoverflow.com/questions/5048561/entity-framework-set-delete-rule-with-codefirst or http://stackoverflow.com/questions/9136255/ef4-1-code-first-how-to-disable-delete-cascade-for-a-relationship-without-navi , perhaps. Trying search for "on delete set null" (which doesn't exist per-se in EF, but ought to lead to similar solutions) – user2864740 Oct 22 '13 at 23:09
-
Thanks for the reply so I have used "on delete set null" for the child entity but when I delete parent entity, whole child entity is removed, not only the foreign key of the child. Still stuck.. – tamikoon Oct 23 '13 at 01:42
1 Answers
2
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);

Samo
- 8,202
- 13
- 58
- 95