2017-06-22 58 views
1

我有数据库模型:enter image description hereLINQ的DELETE生成UPDATE查询的SQL服务器

约束[FK_applications_orders]外键([ORDER_ID])参考文献[DBO] [单]([ORDER_ID])

而且控制器动作:

using (var tx = Database.Database.BeginTransaction()) 
{ 
    var order = Database.Set<Order>().Find(someID); 

    var apps = Database.Set<Applications>().Where(x => x.Order.Id == order.Id).ToList(); 
    Database.Delete(order); 
    tx.Commit(); 
} 

我打开SQL事件探查器来检查这行var apps = Database...产生,并期待在此:

exec sp_executesql N'UPDATE [dbo].[Applications] 
SET [order_id] = NULL 
WHERE (([application_id] = @0) AND ([order_id] = @1)) 
',N'@0 uniqueidentifier,@1 int',@0=SomeId,@1=SomeOtherId 

那么,为什么Delete调用会在SQL Server中生成一个UPDATE查询呢?

+4

如果您注释掉'Database.Delete(订单);'它仍时有发生? – mjwills

+1

我认为您的订单删除导致应用程序表被更新以强制执行您的约束。 – Stuart

+0

@mjwills它不会,如果我注释掉'Database.Delete(order)' –

回答

3

您在订单和应用程序之间有FK约束。

从Orders表中删除时,EF将对Applicatoins表执行更新以强制执行此约束。

例如您有以下表

订单

order_id 
1 
2 

应用

application_id | order_id 
    100  | 1 
    101  | 2 

当你删除一个订单(比如order_id 1)如果EF没有做更新你最终会与

订单

order_id 
2 

应用

application_id | order_id 
    100  | 1 <---- What is this now ??? 
    101  | 2 

所以在更新该字段设置为null。

应用

application_id | order_id 
    100  | null 
    101  | 2