使用DeleteAllOnSubmit删除记录不使用FK约束

时间:2016-06-09 20:00:19

标签: sql-server linq-to-sql entity-framework-6 linqpad

我试图使用Linqpad以便在尝试从表中移除某些记录时使用LINQ而不是TSQL,这是一个"依赖树的一部分"大概跨过10-12桌。所以我在测试数据库中创建了一些表,并尝试使用DeleteAllOnSubmit和SubmitChanges方法。
我收到FK错误。然而,我首先删除子对象。当有FK关系时如何删除(不在FK'上使用级联)?

  

DELETE语句与REFERENCE约束冲突   " FK_OrderItem_Order&#34 ;.冲突发生在数据库"测试",表中   " dbo.OrderItem",c ...

表:

USE [Test]
GO
/****** Object:  Table [dbo].[Order]    Script Date: 6/9/2016 2:50:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Order](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [OrderNum] [varchar](20) NOT NULL,
    [Description] [varchar](100) NULL,
 CONSTRAINT [PK_Order] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[OrderItem]    Script Date: 6/9/2016 2:50:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[OrderItem](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [OrderId] [int] NOT NULL,
    [OrderItemName] [varchar](100) NOT NULL,
    [Qty] [int] NOT NULL,
 CONSTRAINT [PK_OrderItem] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[OrderItem]  WITH CHECK ADD  CONSTRAINT [FK_OrderItem_Order] FOREIGN KEY([OrderId])
REFERENCES [dbo].[Order] ([Id])
GO
ALTER TABLE [dbo].[OrderItem] CHECK CONSTRAINT [FK_OrderItem_Order]
GO

这是我的LINQ声明

List<Order> olist  = (from a in Orders where a.Id == 2 select a).ToList();
List<int> olistidlist = olist.Select (o => o.Id).ToList();

List<OrderItem> oilist = (from a in OrderItems where olistidlist.Contains(a.Id) select a).ToList();

//see results before
olist.Dump();

OrderItems.DeleteAllOnSubmit(oilist);
Orders.DeleteAllOnSubmit(olist);


//save changes
SubmitChanges();

//see results after
olist.Dump();

1 个答案:

答案 0 :(得分:1)

您正在删除OrderItem OrderItem.Id等于olistidlist中的值的OrderItem.OrderId(目前仅为2)。当然,这必须是foreach (var order in Orders.Where(...)) { OrderItems.DeleteAllOnSubmit(order.OrderItems); Orders.DeleteOnSubmit(order); }

顺便说一句,删除父项和子项的更简单方法通常是:

{{1}}

因此,您不必使用Id值移动。