2014-04-08 4 views
0

데이터베이스 테이블의 레코드를 삭제할 수 있는지 또는 Entity Framework를 사용하지 않는지 확인하고 싶습니다. 레코드의 기본 키가 다른 테이블에서 외래 키로 사용되는 경우이 레코드는 삭제할 수 없습니다.Entity Framework를 사용하여 레코드를 삭제할 수 있는지 확인하는 방법?

엔티티 프레임 워크의 Remove 레코드를 삭제하고 특정 번호의 SQL 예외를 가져올 수 있는지 여부를 확인할 수있는 기능이 있습니다. 그러나 성공하면 레코드를 완전히 삭제합니다. 이것은 내가 원하는 것이 아닙니다. 난 그냥 외부 키 관계가있는 다른 테이블을보고 레코드를 삭제할 수 있는지 여부를 확인하고 싶습니다.

매우 직접적인 접근 방식은 하나씩 탐색 속성을 사용하는 것일 수 있습니다. 하지만 좀 더 일반적인 것으로 만들고 싶습니다. 어떤 아이디어든지 높게 평가 될 것이다.

답변

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 
+0

실행 가능한 방법처럼 보이지만 같은 그것은'DbContext'의 API 작동하지 않습니다. Esp. OfType 부분은 POCO와 함께 작동 할 수 없습니다. –

+0

다음과 같이'DbContext'에서'ObjectContext'를 가져올 수 있습니다 :'IObjectContextAdapter adapter = (IObjectContextAdapter) dbContextInstance;' 'ObjectContext objectContext = adapter.ObjectContext;' – Andrew

+0

@ n-rocking이 작동 했습니까? – Andrew

관련 문제