Reputation: 173
Assume I have a class that is in a independent package and that could be used by Multiple object, for ex:
public class TimeSlot
{
[Required]
public int Id { get; set; }
[Required]
public DateTime StartTime { get; set; }
[Required]
public DateTime EndTime { get; set; }
}
Not this TimeSlot can be referenced from both the classes below:
public class Business
{
public int Id { get; set; }
public virtual IList<TimeSlot> OpeningHours { get; set; }
}
and
public class Delivery
{
public int Id { get; set; }
public virtual IList<TimeSlot> DeliveryHours { get; set; }
}
Using Entity Framework code-first, this will result in a TimeSlot
table containing both foreign keys to Business
and Delivery
objects.
Assume I modify a Business
object (clear the list of the OpeningHours
and add new ones in the code) and update it; once updated, the old TimeSlot
records will have the BusinessId
foreign key set to NULL instead of being deleted.
What's the correct implementation in order to delete those records since they are no longer needed (and preferably without polluting the TimeSlot
object)?
Upvotes: 0
Views: 1598
Reputation: 109252
With EF it's pretty elaborate to delete child collection elements. When you clear the collection or remove items from it, EF plays safe and does not assume you want to delete the objects, but only want to break the association.
So you have to remove the child items explicitly:
db.TimeSlots.RemoveRange(business.OpeningHours);
db.SaveChanges();
(RemoveRange
is EF 6, with earlier versions you have to loop through business.OpeningHours
and do db.TimeSlots.Remove()
).
Upvotes: 0
Reputation: 253
Change in OnModelCreating in your DbContext class. Add willCascadeOnDelete to true.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Business>()
.HasOptional(a => a.OpeningHours)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
base.OnModelCreating(modelBuilder);
}
Upvotes: 2