1

Lets say we have a :

class Zoo{
   Id;
   Name;
   List<Animal> Animals;

}
class Animal{
   Id;
   Name;
   ZooId;
}

Normally I would do

  var zooId=1;
  var animalId=1;
  var animal = db.Animals.FirstOrDefault(x=>x.Id==animalId);
  animal.ZooId=zooId;
  db.SaveChanges();

Correct me if I am wrong,but the ef.core would run a Select query and then an update query.

Is there a way to write a code which would produce a single SQL query like:

'Update Animal Set ZooId=1 where Id=1' 

(Preferably by using lambda code)

Thank you!

Mcgri
  • 187
  • 1
  • 11

1 Answers1

1

Try updating it as below. First create object with assigning valid animalId and set ZooId as your requirement. With Property(x => x.ZooId).IsModified = true; it will only update ZooId.

var animal = new Animal() 
{ 
    Id = 1,
    ZooId = 1
}
db.Animals.Attach(animal).Property(x => x.ZooId).IsModified = true;
db.SaveChanges();

Hopefully this link will be helpful How to update only one field using Entity Framework?

Karan
  • 12,059
  • 3
  • 24
  • 40