【问题标题】:How to check whether a record is deletable using Entity Framework?如何使用实体框架检查记录是否可删除?
【发布时间】:2014-04-09 22:56:53
【问题描述】:

我想使用实体框架检查数据库表中的记录是否可删除。如果记录的主键在不同的表中被用作外键,那么这条记录是不可删除的。

我知道我可以运行实体框架的Remove 函数来删除一条记录并查看我是否可以获得任何具有特定编号的SQL 异常。但如果成功,它将完全删除记录。这不是我想要的。我只想通过查看具有外键关系的其他表来检查记录是否可删除。

一种非常直接的方法可能是逐个使用导航属性。但我想让它更通用。任何想法都将受到高度赞赏。

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    加载通过外键指向它的originalEntity 的所有相关端(不是来自它的导航属性,反之亦然):

    IEnumerable<IRelatedEnd> relEnds = ((IEntityWithRelationships) originalEntity).RelationshipManager.GetAllRelatedEnds();
    
     foreach (IRelatedEnd relatedEnd in relEnds)
     {
       if (relatedEnd is EntityReference)
       {
          continue;
       }
    
       relatedEnd.Load();
    
       if (relatedEnd.CreateSourceQuery().OfType<EntityObject>().Any())
       {
         string exceptionMessage = string.Format("{0} cannot be deleted, because {1} refers to it",
                                                                  originalEntity.GetType().Name, 
                                                                  relatedEnd.CreateSourceQuery().OfType<EntityObject>().First().GetType().Name);
    
         throw new Exception(exceptionMessage);
       }
    }
    

    有关更多详细信息,您可能想查看 MSDN 上的 RelatedEnd 类:

    http://msdn.microsoft.com/en-us/library/system.data.objects.dataclasses.relatedend%28v=vs.110%29.aspx

    // Collection of entities, you need these when iterating through entity's related ends
    public class EntityCollection<TEntity> : RelatedEnd
    
    // Models a relationship end with multiplicity 1.
    public abstract class EntityReference : RelatedEnd
    

    【讨论】:

    • 看起来是一种可行的方法,但它不适用于DbContext API。特别是。 OfType&lt;EntityObject&gt; 部分不能与 POCO 一起使用。
    • 您可以从DbContext 中检索ObjectContext,如下所示:IObjectContextAdapter adapter = (IObjectContextAdapter)dbContextInstance; ObjectContext objectContext = adapter.ObjectContext;
    • 谨慎使用relatedEnd.Load();,因为它会从数据库中获取所有数据,然后执行relatedEnd.CreateSourceQuery().OfType&lt;EntityObject&gt;().Any(),如果您有大量行,则会导致服务器性能问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多