0

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();
        }
    }
Daarwin
  • 2,896
  • 7
  • 39
  • 69
  • 1
    I suppose you could take a look at this [example](http://stackoverflow.com/questions/17487577/entity-framework-ef-code-first-cascade-delete-for-one-to-zero-or-one-relations) for a cascade delete. – Mark C. Jun 01 '16 at 13:48
  • 1
    My bad! I just realised that all equipments will be deleted even when i remove iterating all the equipments and setting them to deleted. Because the Ninja owner is marked as [Required] in its model. – Daarwin Jun 01 '16 at 14:16
  • So, is there anything we can help you with here or are your questions answered? And no biggie - don't worry about it. – Mark C. Jun 01 '16 at 14:19
  • Thanks! Yes gues its answered. Im not really trying to acomplish anything but trying to learn. So i guess i know have several more questions. That i should post separeatly. – Daarwin Jun 01 '16 at 14:21
  • Sounds good. Glad you found what you were looking for. – Mark C. Jun 01 '16 at 14:24
  • You can also replace db.Entry(ninja).State = EntityState.Deleted; with db.Ninjas.Remove(ninja); – poppertech Jun 01 '16 at 14:32

0 Answers0