2014-10-13 6 views
0

테스트 용 mock dbcontext를 구축 중입니다. 하지만 Entity Framework에서 set 함수를 다시 구현해야합니다.DbContext 설정 방법

이 지금은 내 코드입니다 :

public DbSet<TEntity> Set<TEntity>() 
     where TEntity : class, IObjectState 
{ 
    foreach (PropertyInfo property in GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic)) 
    { 
     if (property.PropertyType == typeof(FakeDbSet<TEntity>)) 
      return property.GetValue(this, null) as FakeDbSet<TEntity>; 
    } 
    throw new Exception("Type collection not found"); 
} 

내 문제는 내가이 개 서브 클래스 두 슈퍼 클래스 데이터 집합을 저장할 것입니다.

private DbSet<BaseContact> Contacts { get; set; } 

를하지만 유형 연락 다시 액세스하려고 할 때 먼저 슈퍼 클래스를하지 않았기 때문에 나는 예외를 얻을 것이다 : 그래서 나는 다음과 같이 데이터 세트를합니다. 내가 어떻게 해?

+0

'Contact'의 경우 무엇을 반환하고 싶습니까? 새로운'FakeDbSet '을 만들 수 있습니까? – Bas

+0

그럴 수는 있지만 그 데이터베이스에 더 추가하지는 않겠습니다. 기본 연락처에서 연장 된 연락처와 이메일 주소는 기본 연락처에서 연장됩니다. – kevingoos

답변

0

나는 당신이이 일에 대해거야 방법에 동의하지만, 즉각적인 문제에 대한 하나 개의 솔루션은 TEntity의 기본 형식에 대한 속성 '제네릭 형식 인수가 더 결과가 발견되지 않으면 경우 테스트하는 것입니다 :

public DbSet<TEntity> Set<TEntity>() 
     where TEntity : class, IObjectState 
{ 
    var propertyInfos = GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic); 

    foreach (PropertyInfo property in propertyInfos) 
    { 
     if (property.PropertyType == typeof(FakeDbSet<TEntity>)) 
      return property.GetValue(this, null) as FakeDbSet<TEntity>; 
    } 

    // no joy, test for base class(es) 
    var baseType = typeof(TEntity).BaseType; 

    while(typeof(object) != baseType) 
    { 
     foreach(var property in propertyInfos) 
     { 
      if(property.PropertyType == 
       typeof(FakeDbSet<>).MakeGenericType(baseType) 
      { 
       var baseTypeDbSet = property.GetValue(this, null); 

       var entityDbSet = // you will need to convert FakeDbSet<TBaseType> to FakeDbSet<TEntity> 

       return entityDbSet; 
      } 
     } 

     baseType = baseType.BaseType; 
    } 

    throw new Exception("Type collection not found"); 
} 
+0

아침에 시도해 보겠습니다. 그러나 컨텍스트를 훨씬 단순하게 만들었 기 때문에 이것이 좋은 방법이 아니라고 말하면 이해합니다. 그래서 우리는 이유 때문에 이것을했습니다. – kevingoos