简体   繁体   中英

How to only update specific fields in Entity Framework (Core)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM