减少数据库调用

Reducing database calls

在 1 个数据库调用中执行此操作的最佳方法是什么?

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; 
}

我的想法:

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

但是不得不声明额外的所有者变量感觉很糟糕。我有一堆这样的 if 语句,所以我必须创建一堆额外的不需要的所有者变量。

我怎样才能做得更好?

您只需检查是否可以从数据库中获取所有者的 ContactNumber,而不是整个所有者,因为您不会更新它。你甚至可以在不使用 "needless" 变量的情况下做到这一点:

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

因此,如果找不到所有者编号,则不会进行任何更改。