【发布时间】:2020-12-03 00:03:44
【问题描述】:
我正在编写一个应用程序,该应用程序从外部 API 提取数据并使用 Entity Framework 将其存储到我的 SQL Server 数据库中。我每天都从这个 API 中提取数据,所以如果一行已经存在,则记录将被更新,否则将创建一个新记录。这是通过检查 Id 来完成的。
现在我遇到的问题是我只希望 EF 更新 BranchId 和 CustomerNameTopdesk。 CustomerNamePRTG 值是我自己手动添加到数据库中的。所以现在当记录更新时,它被设置回 NULL,我手动插入的值将丢失。
更新前
更新后
来自 API 的数据从 JSON 反序列化并作为 List<Customers>. 存储在 data 变量中.如您所见,它当前正在更新整个 Customer 记录,包括为 NULL 的 CustomerNamePRTG
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();
}
型号
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; }
【问题讨论】:
标签: c# asp.net-core entity-framework-core