我正在构建一个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;
}
}
有更有效的方法吗?我可以以某种方式使用IsModfied或Attach函数吗?