1

EF 6. Im trying to figure out the most fluid way to update an EF graph. So i have a ninja model with a list of NinjaEquipments. Lets say the ninja has three equipments like the following

Ninja (Id:99)

  • EquipmentID 1, name: "Tool"
  • EquipmentID 2, name: "Sword"
  • EquipmentID 3, name: "Pokemon"

I send the model to a web application to be edited and the following is returned.

Ninja (Id:99)

  • EquipmentID 1, name: "Tool"
  • EquipmentID 3, name: "My Favourite Pokemon"
  • EquipmentID 0 because its new, name: "Unicorn"

So what has happened is ninja has

  1. Lost item with id 2 "Sword"
  2. renamed item with id 3 to "My Favourite Pokemon"
  3. gained a new item with name "Unicorn"

How would i go about updating the model in the db context the easiest way. The only way i would be able to do it know is to look for new items, look for changed items and compare the updated model with the saved model to see wich items have been deleted. Is this the correct way or is there a way to give EF the new updated model and tell it that NinjaEquipments should reflect it?

Classes:

   public class NinjaEquipment
{
    public int Id { get; set; }
    public string Name { get; set; }
    public EquipmentType Type { get; set; }

    [Required]
    public Ninja Ninja { get; set; }
}

 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; }
    }
Daarwin
  • 2,896
  • 7
  • 39
  • 69
  • Well, you can always delete all the equipment the ninja had and just add all the new equipements he now has, if you dont't do that, then of course : 1 ) check for new items, 2) check for changed item, 3) check for deleted items – Antoine Pelletier Jun 01 '16 at 15:43
  • Yes I've thought about that. I'm for a confirmation that there is no straight forward EF mechanic that does it for me before I proceed. – Daarwin Jun 01 '16 at 15:45
  • Ok, if your working with different context, you can always use function like db.ApplyCurrentValues("objectname"); and db.attach(); I'm almost sure that if it's really an entity model you have as an input, there is some way to save it somehow and let entity traducer work for you, i don't know if it will be faster or slower though – Antoine Pelletier Jun 01 '16 at 15:52
  • I cant find ApplyCurrentValues. Is this in EF6? – Daarwin Jun 02 '16 at 12:28
  • Not anymore... http://stackoverflow.com/questions/20451461/save-detached-entity-in-entity-framework-6 – Antoine Pelletier Jun 02 '16 at 14:41

0 Answers0