我想简单介绍一下我的目标。我们在应用程序中保留了远程数据库(第三方)的本地副本。为了下载信息,我们使用一个API。目前,我们会按计划下载信息,然后将新记录插入到本地数据库中或更新现有记录。以下是目前的工作方式:
public void ProcessApiData(List<Account> apiData)
{
// get the existing accounts from the local database
List<Account> existingAccounts = _accountRepository.GetAllList();
foreach(account in apiData)
{
// check if it already exists in the local database
var existingAccount = existingAccounts.SingleOrDefault(a => a.AccountId == account.AccountId);
// if its null then its a new record
if(existingAccount == null)
{
_accountRepository.Insert(account);
continue;
}
// else its a new record so it needs updating
existingAccount.AccountName = account.AccountName;
// ... continue updating the rest of the properties
}
CurrentUnitOfWork.SaveChanges();
}
这个方法能够正常工作,但感觉还有改进的空间。
- 每个实体都有一个这样的方法,它们都做同样的事情(只是更新不同的属性)或插入不同的实体。有没有办法使这更加通用?
- 这似乎涉及到很多数据库调用,有没有一种“批量”处理的方式?我看了一下这个包,也在其他帖子中见过它 https://github.com/loresoft/EntityFramework.Extended 但它似乎只关注于使用相同值批量更新单个属性,至少我目前是这么认为的。
如果您有任何建议可以帮助我改进这个方法,我将不胜感激。我对C#还比较新,仍在寻找最佳实践。
我正在使用 .net 4.5.2 和 Entity Framework 6.1.3,后端数据库是 MSSQL 2014