2010-07-03 80 views
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); 

有沒有更好的辦法?

預先感謝您!

回答

3

如果你的規則是,你不能有孤立的地址,你可能會從以下順序更好的性能和更簡單的代碼維護:

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

謝謝你,我會在幾天檢查的答覆! – 2010-08-06 07:59:40