我正在构建一个Windows服务,从第三方API获取所有网络,并将这些网络插入/更新到我们的本地数据库中。以下是我的实体:
public partial class Networks
{
public string networkID { get; set; }
public int organizationID { get; set; }
public string type { get; set; }
public string name { get; set; }
public string time_zone { get; set; }
public string tags { get; set; }
}
目前我通过API返回的所有网络进行迭代,检查是否存在ID,如果存在,则检查每个字段,如果其中一个字段不匹配,则全部更新。
public void SyncNetworks()
{
List<Networks> all_networks = APICaller.GetNetworkList();
foreach(var network_from_api in all_networks)
{
var network_in_database = db.it_asset_meraki_networks.FirstOrDefault(
n => n.network_id == network_from_api.network_id);
if (network_in_database == null)
db.it_asset_meraki_networks.Add(network_in_meraki);
else
CheckAndSyncNetworkFields(network_from_api, network_in_database);
}
db.SaveChanges();
}
private void CheckAndSyncNetworkFields(Networks network_from_api, Networks network_in_database)
{
if(network_in_database.name != network_from_api.name
|| network_in_database.organizationID != network_from_api.organizationID
|| network_in_database.type != network_from_api.type
|| network_in_database.tags != network_from_api.tags
|| network_in_database.time_zone != network_from_api.time_zone)
{
network_in_database.name = network_from_api.name;
network_in_database.organizationID = network_from_api.organizationID;
network_in_database.type = network_from_api.type;
network_in_database.tags = network_from_api.tags;
network_in_database.time_zone = network_from_api.time_zone;
}
}
有没有更有效率的方法?我是否可以通过使用IsModified或Attach函数来解决问题?