Entity framework 减少数据库调用

Entity framework 减少数据库调用,entity-framework,database-performance,iqueryable,Entity Framework,Database Performance,Iqueryable,在1dB呼叫中,最好的方法是什么 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).

在1dB呼叫中,最好的方法是什么

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语句,所以我必须创建一堆多余的所有者变量


如何才能更好地做到这一点?

您只需检查是否可以从数据库中获取所有者的
联系人号码,而不是整个所有者,因为您不需要更新它。您甚至可以不用使用“不必要的”变量:

dbDog.OwnerContactNumber = 
     dbContext.Owners
              .Where(i => i.Value == dog.OwnerID)
              .Select(o => o.ContactNumber)
              .FirstOrDefault() ?? dbDog.OwnerContactNumber;
因此,如果没有找到所有者编号,则不会进行任何更改