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?
I think you're just looking for an Upsert (Insert or Update) in Entity framework.
You could use AddOrUpdate() for this, see here.
.Added or .Modified could be use as well, as seen in the first answer here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With