Home > front end >  EF Core Set FK to NULL for child entity with soft delete parent entity record
EF Core Set FK to NULL for child entity with soft delete parent entity record

Time:12-19

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

CodePudding user response:

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. And it is better to use For loop, it doesn' t create a copy

var customerId=1;
var customer = dbContext.Customers.
         .Include(i=>i.Orders).First( c=> c.Id == customerId );

customer.IsDeleted = true;
for(var i==0; i< customer.Orders.Count; i  )
{
   customer.Orders[i].CustomerId = null;
   customer.Orders[i].ArchivedBy = user;
   customer.Orders[i].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();

for(var i==0; i< customerOrders.Count; i  )
{
   customerOrders[i].CustomerId = null;
   customerOrders[i].ArchivedBy = user;
   customerOrders[i].ArchivedDate = DateTime.Today()
);

CodePudding user response:

Please define CustomerId as nullable

public {datatype}? CustomerId { get; set; }

Example

public int? CustomerId { get; set; }
  • Related