批处理实体框架查询以提高效率

时间:2018-10-26 01:07:48

标签: entity-framework linq-to-entities

如果下面有我在每个循环中查询数据库的代码段,是否有办法通过只运行一次查询并传递列表或集合来使其更有效?

using (var dbContext = new YogabandyContext(ybDatabaseConnectionString))
{
    foreach (StripeBalanceTransaction transaction in balanceTransactions)
    {
        var profileCharge = dbContext.Charges.Where(i => i.BalanceTransactionId == transaction.Id).FirstOrDefault();

        if (profileCharge == null)
        {
            // do some error work
        }
        else
        {
            profileCharge.PayoutStatus = PayoutStatus.Succeeded;
            profileCharge.PayoutId = payoutId;
            profileCharge.PayoutObjectResponse = stripeEvent.StripeResponse.ObjectJson;
        }
    }

    dbContext.SaveChanges();
}

1 个答案:

答案 0 :(得分:1)

您可以重构此方法。将仅对数据库执行两次查询,而不是balanceTransactions.Count + 1次:

var ids = balanceTransactions.Select(x => x.Id).ToList();

//first query
var profileCharges = dbContext.Charges
                         .Where(x => ids.Contains(x.BalanceTransactionId).ToList();

var existedIds = profileCharges.Select(x => x.BalanceTransactionId).ToList();
var notExisted = balanceTransactions.Where(x => !existedIds.Contains(x.Id)).ToList()
foreach(var transaction in notExisted)
{
    //do some error work
}

profileCharges.ForEach(x => 
{
     x.PayoutStatus = PayoutStatus.Succeeded;
     x.PayoutId = payoutId;
     x.PayoutObjectResponse = stripeEvent.StripeResponse.ObjectJson;
})

//second query
dbContext.SaveChanges();