4
我有很多對許多人和地址LINQ to SQL。級聯刪除sumulation
關係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
}
當我刪除人我必須刪除AddressPerson行(這很容易),以及適當的地址行,但只有當沒有外部引用的地址,除了一個被刪除。
在數據庫級別實現級聯刪除會更聰明,但我如何在純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);
有沒有更好的辦法?
預先感謝您!
謝謝你,我會在幾天檢查的答覆! – 2010-08-06 07:59:40