Reputation: 65
I am building a windows service to pull all networks from a third party API and insert/update those networks to our local DB. Here is my Entity:
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; }
}
Currently I iterate through all the networks returned by the api, check if the id exists, if it does check each field and if they one of the fields does not match update them all.
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;
}
}
Is there a more efficient way of doing this? Could I somehow use the IsModfied or Attach functions?
Upvotes: 3
Views: 596