实体框架:检查实体的外键使用的所有关系

实体框架:检查实体的外键使用的所有关系

问题描述:

我有一个实体,我们称之为 CommonEntity 有作为,在许多其他实体的外键的主键。随着应用开发这些链接将继续增长。

I have an entity, let's call it CommonEntity that has a primary key used as a foreign key in many other entities. As the application is developed these links will continue to grow.

我想办法,看看 CommonEntity 可以安全地删除(即它不被任何其他实体)。

I'd like a way to see if CommonEntity can be safely deleted (i.e. it's not used by any other entities).

我知道我能做到

if(!ce.EntityA.Any() && !ce.EntityB.Any() ... && !ce.EntityN.Any())
{
   //Delete
}

但我希望的方式来只是自动检查所有的关系,因为我不喜欢有回来,改变这个code手动每次我们增加一个新的关系的想法。也许有东西在EF4 +,我不知道呢?

but I'm hoping for a way to just check all of the relationships automatically, as I don't love the idea of having to come back and change this code manually every time we add a new relationship. Perhaps there is something in EF4+ that I'm not aware of?

我想这可能是可以使用的交易范围,只是尝试和删除对象,如果失败回滚,但我不知道是否有任何副作用,这种方法。

I thought it might be possible to use a transaction scope to just try and delete the object and roll it back if it fails, but I wasn't sure if there were any adverse side effects with this approach.

有没有更好的方法?

编辑:看起来VS2012采用了EF5尽管该项目是.NET 4中,所以它创造了模型波苏斯即使它从数据库生成

Looks like VS2012 has used EF5 even though the project is .Net 4, so it has created the model with POCOs even though it was generated from a DB.

只是让它失败。如果实体有许多关系,这验证可能是非常沉重的。

Just let it fail. If the entity has many relationships, that verification could be really heavy.

public bool TryDelete(int id)
{
    try
    {
        // Delete
        return true;
    }
    catch (SqlException ex)
    {
        if (ex.Number == 547) return false; // The {...} statement conflicted with the {...} constraint {...}
        throw; // other error
    }
}