Reducing database calls

131 Views Asked by At

What would be the best way to do this in 1 DB call?

if (dbContext.Owners.Any(i => i.Value == dog.OwnerID)) //Check if owner exists in db
{
    //Assign the owner's contact number to the dog entry
    dbDog.OwnerContactNumber = dbContext.Owners.First(i => i.Value == dog.OwnerID).ContactNumber; 
}

My thoughts:

Owner owner = dbContext.Owners.FirstOrDefault(i => i.Value == dog.OwnerID); //Get the owner
if (owner)
{
    dbDog.OwnerContactNumber = owner.ContactNumber; //Assign the contact number
}

But it feels bad having to declare that extra owner variable. And I have a bunch of these if statements, so I'll have to create a bunch of extra unneeded owner variables.

How can I do this better?

1

There are 1 best solutions below

0
On BEST ANSWER

You only have to check if you can get an owner's ContactNumber from the database, not the entire owner, because you don't update it. And you can even do it without using a "needless" variable:

dbDog.OwnerContactNumber = 
     dbContext.Owners
              .Where(i => i.Value == dog.OwnerID)
              .Select(o => o.ContactNumber)
              .FirstOrDefault() ?? dbDog.OwnerContactNumber;

So if no owner number is found, no change is made.