I am trying to set CustomerID to NULL for the Orders when setting Isdeleted = true (soft delete) for Customer (parent entity).
It is updating both 'archivedBy' and 'ArchivDate', but not updating the CustomerID to NULL.
Is there any option other than fetching the Orders separately and setting the CustomerID to NULL?
Below is the code I am using to update the data.
var customer = dbContext.Customers.Find(1);
customer.IsDeleted = true;
customer.Orders.ForEach(r =>
r.CustomerId = NULL;
r.ArchivedBy = user;
r.ArchivedDate = DateTime.Today()
);
dbContext.Customers.Update(customer);
dbContext.SaveChanges();
Please define CustomerId as nullable
public {{datatype}}? CustomerId { get; set; }
Example public int? CustomerId { get; set; }
you don't need to call update customer, it brakes the code and don't use Find, you have to include Orders to your db set
var customerId=1;
var customer = dbContext.Customers.
.Include(i=>i.Orders).First( c=> c.Id == customerId );
customer.IsDeleted = true;
customer.Orders.ForEach(r =>
r.CustomerId = NULL;
r.ArchivedBy = user;
r.ArchivedDate = DateTime.Today()
);
dbContext.Entry(customer).State = EntityState.Modified; //optional
dbContext.SaveChanges();
if it still not working, try to modify Orders, instead of customer.Orders
var customerOrders= dbContext.Orders.Where(o=> o.CustomerId==customerId).ToList();
customerOrders.ToList().ForEach(r =>
r.CustomerId = NULL;
r.ArchivedBy = user;
r.ArchivedDate = DateTime.Today()
);
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.