Using Entity Framework 6. I have a Ninja model that looks like this:
public class Ninja
{
public Ninja(Clan clan )
{
Clan = clan;
EquipmentOwned = new List<NinjaEquipment>();
}
public Ninja()
{
EquipmentOwned = new List<NinjaEquipment>();
}
public int Id { get; set; }
public Clan Clan { get; set; }
public int ClanId { get; set; }
public bool ServedInOnibawan { get; set; }
public string Name { get; set; }
public List<NinjaEquipment> EquipmentOwned { get; set; }
}
Im learning how to best delete graphs the EF way. Im receiving an id and i want to delete the ninja and all its NinjaEquipments. This is how i do it. My question is if its the most straight forward way or if there is a way where i could attach a ninja entity with the equipments all and have the ninja deleted leading to all equipments also being deleted?
//Deletes ninja AND all connected equipments
public static void DeleteNinja(int id)
{
using (var db = new NinjaDbContext())
{
var ninja = db.Ninjas.Where(n => n.Id == id).Single();
db.Entry(ninja).State = EntityState.Deleted;
foreach (var eq in ninja.EquipmentOwned)
{
db.Entry(eq).State = EntityState.Deleted;
}
db.SaveChanges();
}
}