Entity Framework 6 Synthetic Table with External Source

I am creating a windows service to pull all networks from a third party API and insert / update those networks into our local DB. Here is my essence:

    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; }
}

      

I am currently iterating over all the networks returned by the api, checking if the id exists, if it checks each field and if one of the fields does not match their update.

        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 to do this? Can I use IsModfied or Attach in any way?

+3


source to share


1 answer


I think you are just looking for Upsert (Insert or Update) in the Entity framework.

You can use AddOrUpdate()

for this, see here .



.Added

or .Modified

can also be used as seen in the first answer here

+1


source







All Articles