pgerchev pgerchev - 3 months ago 16
C# Question

Entity Framework Navigation Collection Property Delete

I have two entities as the following:

public class FirstEntity
{
public int Id { get; set; }

public ICollection<SecondEntity> SecondEntityCollection { get; set; }
}

public class SecondEntity
{
[Key]
[Column(Order = 0)]
public int FirstEntitySomeId { get; set; }

[Key]
[Column(Order = 1)]
public int SecondEntityId { get; set; }
}


My
ModelBuilder
is set as following

modelBuilder.Entity<FirstEntity>()
.HasMany(x => x.SecondEntity)
.WithRequired()
.HasForeignKey(x => x.FirstEntitySomeId);


When deleting a
FirstEntity
object I do the following:

var firstEntity=this.context.FirstEntities.Where(x=>x.Id==someId);
firstEntity.SecondEntityCollection.Clear();
this.context.FirstEntities.Remove(firstEntity);
this.context.SaveChanges();


However I still get the following exception:


The DELETE statement conflicted with the REFERENCE constraint "....". The conflict occurred in database "Database", table "dbo.SecondEntity", column 'FirstEntitySomeId'.


How can I properly clear the collection before deleting the
firstEntity
object?

It's worth mentioning that I am trying to avoid cascade deleting. I do want to delete the orphan entries in the database. However if the best solution/practice is to use cascade delete I will use it.

Is this possible?

Answer

You can try as shown below.

var firstEntity=this.context.FirstEntities
                       .Where(x=>x.Id==someId)
                       .Include(s => s.SecondEntityCollection);

this.context.FirstEntities.Remove(firstEntity);

foreach (var s in firstEntity.SecondEntityCollection.ToList())
  {
     this.context.SecondEntityCollection.Remove(s);
  }

this.context.SaveChanges();