I'm writing an application which is pulling data from an external API and storing this into my SQL Server database using Entity Framework. I pull data from this API every day so if a row already exists the record will be updated, otherwise a new record will be created. This is done by checking for the Id.
Now the problem I'm having is that I only want EF to update the BranchId and CustomerNameTopdesk. The CustomerNamePRTG value is added into the database by myself by hand. So right now when the record is updated it's set back to NULL and my manually inserted values will be lost.
Before Updating

After Updating
The data from the API is deserialized from JSON and stored in the data variable as a List<Customers>. I'm using the following code to check if a record already exists by Id and updating it, otherwise creating a new one. As you can see it's currently updating the whole Customer record including CustomerNamePRTG which is NULL
string apiResponse = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<List<Customers>>(apiResponse);
foreach (Customers customer in data)
{
if (db.Customers.Any(x => x.BranchId == customer.BranchId))
{
db.Customers.Update(customer);
}
else
{
db.Customers.Add(customer);
}
db.SaveChanges();
}
Model
public class Customers
{
[Key]
[JsonProperty("id")]
public string BranchId { get; set; }
[JsonProperty("name")]
public string CustomerNameTopdesk { get; set; }
public string CustomerNamePRTG { get; set; }
}
DbContext
public DbSet<Customers> Customers { get; set; }
You have to update entity returned by the EF.
string apiResponse = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<List<Customers>>(apiResponse);
foreach (Customers customer in data)
{
var current = db.Customers.Find(customer.BranchId);
if (current != null)
{
db.Entry(current).CurrentValues.SetValues(customer);
}
else
{
db.Customers.Add(customer);
}
db.SaveChanges();
}
You should be able to assign value to single field only.
string apiResponse = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<List<Customers>>(apiResponse);
foreach (Customers customer in data)
{
var record = db.Customers.Find(customer.BranchId);
if (record != null)
{
record.BranchId = customer.BranchId;
// as many fields as you need
db.Customers.Update(record );
}
else
{
db.Customers.Add(customer);
}
db.SaveChanges();
}
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