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

Deleting records using DeleteAllOnSubmit not working with FK contstraints

我尝试使用 Linqpad 以便在尝试从 table 中删除一些记录时使用 LINQ 而不是 TSQL,"dependency tree" 的一部分可能跨越 10-12 [=21] =]秒。因此,我在测试数据库中创建了一些 tables 并尝试使用 DeleteAllOnSubmit 和 SubmitChanges 方法。
我收到 FK 错误。然而,我首先删除了子对象。有FK关系时如何删除(不在FK上使用级联)?

The DELETE statement conflicted with the REFERENCE constraint "FK_OrderItem_Order". The conflict occurred in database "Test", table "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();

您正在删除 OrderItem,其中 OrderItem.Id 等于 olistidlist 中的值(目前只有 2 个)。当然这个必须是OrderItem.OrderId.

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

foreach (var order in Orders.Where(...))
{
    OrderItems.DeleteAllOnSubmit(order.OrderItems);
    Orders.DeleteOnSubmit(order);
}

因此您不必移动 Id 值。