gpt4 book ai didi

.net - LINQ 到 SQL。级联删除模拟

转载 作者:行者123 更新时间:2023-12-01 02:55:30 26 4
gpt4 key购买 nike

我在人和地址之间有多对多的关系

Person { Id, ... }
Address { Id, ... }
Address2Person { Id, PersonId, AddressId }

DBML 生成的类看起来像(图中有 PK 和 FK):
class Person {
Id, Address2Person
}

class Address2Person {
Id, Person, PersonId, Address, AddressId
}

class Address {
Id, Address2Person
}

当我删除 person 时,我必须删除 AddressPerson 行(这很容易)以及适当的 Address 行,但前提是没有对 address 的外部引用,除非删除一个。

在数据库级别实现级联删除可能更聪明,但我如何在纯 LINQ 2 SQL 中模拟这一点?

最后我编写了这样的代码:
// finding out addresses to delete
var addressesToDelete =
(from ap in DataBase.Address2Person
group ap by ap.Address
into g
where g.All(x => x.PersonId == personId2Delete)
select g.Key).ToList();

// killing references
DataBase.Address2Person.DeleteAllOnSubmit(
DataBase.Address2Person.Where(x => x.PersonId == personId2Delete));

// killing addresses
DataBase.Address.DeleteAllOnSubmit(addressesToDelete);

有没有更好的办法?

先感谢您!

最佳答案

如果您的规则是不能有孤立地址,您可能会从以下顺序获得更好的性能和更容易的代码维护:

DataBase.Address2Person.DeleteAllOnSubmit(
DataBase.Address2Person.Where(x => x.PersonId == personId2Delete));
DataBase.Address.DeleteAllOnSubmit(
DataBase.Address.Where(x => !x.Address2Person.Any());

关于.net - LINQ 到 SQL。级联删除模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3172750/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com