コード例 #1
0
 public void SaveUpdatedEquipment(NinjaEquipment equipment, int ninjaId)
 {
     //paying the price of not having a foreign keys!
     //reason #857 why I prefer foreign keys!
     using (var context = new NinjaContext())
     {
         ////Not Work! (There is no foreign key!)
         //context.Entry(equipment).State = EntityState.Modified;
         //var ninja = context.Ninjas.Find(ninjaId);
         //equipment.Ninja = ninja;
         //context.SaveChanges();
         var equipmentWithNinjaFromDatabase = context.Equipment.Include(n => n.Ninja)
                                              .FirstOrDefault(e => e.Id == equipment.Id);
         if (equipment.Ninja.Id != ninjaId)
         {
             var ninja = context.Ninjas.Find(ninjaId);
             equipment.Ninja = ninja;
         }
         context.Entry(equipmentWithNinjaFromDatabase).CurrentValues.SetValues(equipment);
         context.SaveChanges();
     }
 }