简体   繁体   English

对于具有软删除父实体记录的子实体,EF Core 将 FK 设置为 NULL

[英]EF Core Set FK to NULL for child entity with soft delete parent entity record

I am trying to set CustomerID to NULL for the Orders when setting Isdeleted = true (soft delete) for Customer (parent entity).在为客户(父实体)设置 Isdeleted = true(软删除)时,我试图将订单的 CustomerID 设置为 NULL。

It is updating both 'archivedBy' and 'ArchivDate', but not updating the CustomerID to NULL.它正在更新“archivedBy”和“ArchivDate”,但没有将 CustomerID 更新为 NULL。

Is there any option other than fetching the Orders separately and setting the CustomerID to NULL?除了单独获取订单并将 CustomerID 设置为 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请将 CustomerId 定义为可为空

public {{datatype}}?公共{{数据类型}}? CustomerId { get;客户 ID { 获取; set;放; } }

Example public int?示例公共 int? CustomerId { get;客户 ID { 获取; 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如果它仍然不起作用,请尝试修改 Orders,而不是 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()
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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