LINQ to SQL。级联删除模拟

时间:2010-07-03 20:15:04

标签: .net linq linq-to-sql

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

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行,但只有在没有外部引用地址的情况下才会删除。

可能在数据库级别实现级联删除会更聪明,但我如何在纯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);

有更好的方法吗?

提前谢谢!

1 个答案:

答案 0 :(得分:3)

如果您的规则是您无法拥有孤立的地址,则可以通过以下顺序获得更好的性能和更轻松的代码维护:

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