I'm serializing data from EF core to JSON file. My model and configuration:
public class Customer
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
public class Order
{
[Key]
public Guid Id { get; set; }
public Guid CustomerGuid { get; set; }
[JsonIgnore]
public virtual Customer Customer { get; set; }
public string OrderType { get; set; }
}
public class CustomerConfiguration : IEntityTypeConfiguration<Customer>
{
public void Configure(EntityTypeBuilder<Customer> builder)
{
builder.HasMany(p => p.Orders).WithOne(d => d.Customer).HasForeignKey(d => d.CustomerGuid);
}
}
public class OrderConfiguration : IEntityTypeConfiguration<Order>
{
public virtual void Configure(EntityTypeBuilder<Order> builder)
{
builder.HasOne(p => p.Customer).WithMany(p => p.Orders).HasForeignKey(d => d.CustomerGuid);
}
}
I serialized one customer to JSON file:
{
"Id": "18a55fea-89cd-438a-bae0-4954193807bf",
"Name": "Customer1",
"Orders": [
{
"Id": "f253837f-5428-405a-880e-2af2b597094c",
"CustomerGuid": "18a55fea-89cd-438a-bae0-4954193807bf",
"OrderType": "OrderType1"
},
{
"Id": "0a288fe3-0a00-4372-810f-3d682f82f1dc",
"CustomerGuid": "18a55fea-89cd-438a-bae0-4954193807bf",
"OrderType": "OrderType2"
},
{
"Id": "0df4a724-598c-44d7-a6eb-4d597501520f",
"CustomerGuid": "18a55fea-89cd-438a-bae0-4954193807bf",
"OrderType": "OrderType0"
}
]
}
Now, I changed "Name": "Customer1"
to "Name": "Customer2"
from JSON file and I want to update DB also from EF core. I wish in DB customer with "Id": "18a55fea-89cd-438a-bae0-4954193807bf"
's Name
would be Customer2
. I can delete customer with this Id and create new customer, but I want to update it. In this case, I can do:
var customerFromJson = JsonConvert.DeserializeObject<Customer>(json);
var customerFromDB = context.GetEntities<Customer>().Single(c => c.Id == customerFromJson.Id);
customerFromDB.Name = customerFromJson.Name;
context.SaveChanges();
But there can be other properties except the Name
property and I don't want to do this manually. Is there any good solution, hard codes or other ways to solve this problem?