2011-05-02 5 views
0

의 컬렉션 속성을 가져옵니다 :내가 DbSet 수집 일련의 속성을 가진 클래스 MyDatabaseContext이 특정 유형

public DbSet<EntityA> EntitiesA { get; set; } 
public DbSet<EntityB> EntitiesB { get; set; } 
public DbSet<EntityC> EntitiesC { get; set; } 

내가 엔티티의 종류 주어진 컬렉션의 이름을 얻을 필요가있다.
예를 들어, "EntityB"가 있고 "EntitiesB"라는 결과를 얻고 싶습니다.

MyDatabaseContext가 자동으로 생성되므로 (T4 템플릿) switch-case 문을 피하고 싶었습니다.

+0

:

using System.Data.Entity.Infrastructure; using System.Data.Objects; ((IObjectContextAdapter)_dbContext).ObjectContext.CreateObjectSet<EntityB>() 

설명 :

_dbContext is Context class inherting from DbContext. EntitiesB is DbSet<EntityB> defined in Context class. 

예 내가 옳다 또는이 페이지의 다른 방문자가 이런 식으로 뭔가를 필요로하는 경우, 단지 쉽게 다음 코드를 사용 재산의 이름이 필요 하신가요? –

+0

좋은 지적. 변수 'EntitiesC'의 유형 'EntityC'는 설계시에도 널리 사용 가능해야합니다. – ProfK

답변

1

을 당신이 만약 단지 너 여기 부동산의 이름을 원해. 나는 사냥꾼이 준 대답을 다듬을 뿐이다. 동일한 메소드를 반환 유형으로 문자열과 함께 사용할 수 있습니다.

public string GetEntitiName<T>() where T : class 
    { 
     PropertyInfo propInfo = typeof(MyDatabaseContext).GetProperties().Where(p => p.PropertyType == typeof(DbSet<T>)).FirstOrDefault(); 
     string propertyName = propInfo.Name; //The string has the property name .. 
     return propertyName;  
    } 

나는 당신의 상황과 비슷한 샘플을 시도했다. List를 DbSet으로 바꾸어보십시오.

class Program 
    { 
     public static void GetEntities<T>() where T : class 
     { 

      var info = typeof(TestClass1).GetProperties().Where(p => p.PropertyType == typeof(List<T>)); 

      Console.WriteLine(info.FirstOrDefault().Name); 
     } 

     static void Main(string[] args) 
     { 
      GetEntities<int>(); 
      Console.ReadLine(); 
     } 
    } 
    public class TestClass1 
    { 
     public List<int> IntTest { get; set; } 
     public List<double> DoubleTest { get; set; } 
     public List<string> IStringTest { get; set; } 
    } 

이 샘플은 작동합니다.

+0

나는 typeof (DbSet )에이 오류가 발생합니다 : 유형 'T'는 'TEntity'매개 변수로 사용하기 위해 참조 유형이어야합니다. .Data.Entity.DbSet ' –

+0

pls 편집 된 솔루션을 시도하십시오 – gordanvij

+0

일반 형식 정의에서 typeof를 사용하려면 typeof (Dictionary <,>) –

0

생성 된 파일이 부분 클래스, 당신은 새 파일을 작성하고 키워드 partial를 사용하여 같은 이름의 클래스를 선언 할 수 다음 원하는 컬렉션을 반환하는 방법 ...

+0

그러나 그때 나는 정말로 피하고 싶었던 switch-case 경로를 가야 할 것입니다 ... –

+0

다른 옵션은 여기에 표시되지 않지만 ... : 1. 각 파일에서 하나의 컨텍스트를 사용하십시오 (여러 edmx). 2.'class '을 생성하고 'DbSet ' 속성을 갖도록합니다. 죄송합니다 그게 도움이되지 않으면 ... – BrunoLM

0

실제로이 작업을 직접 수행하지는 않았지만 원하는 작업이 리플렉션을 사용하여 해당 제네릭 형식 매개 변수가있는 "DbSet"유형의 속성을 찾는 것입니다. 다음 가상 C#을 시작해야합니다.

foreach (FieldInfo field in this.GetType()) 
{ 
    if (field.FieldType.IsGenericType) 
    { 
    foreach (Type param in field.FieldType.GetGenericArguments()) 
    { 
     if (param.Name == soughtType) 
     { 
     return field.Name; 
     } 
    } 
    } 
} 
1

나는 이것이 이전 페이지라는 것을 알고 있지만, 내 대답은 아마도 여기를 참조하는 다른 사람들에게 유용 할 것입니다. (나와 같은)

EntitiesB.Where(a=>a.bla=="blabla")과 같이 쿼리를 실행하려면 EntitiesB에 액세스하려고한다고 생각합니다. 왜 당신을

Ilist result = ((IObjectContextAdapter)_dbContext).ObjectContext.CreateObjectSet<EntityB>().Where(b=>b.bla=="blabla").ToList(); 
관련 문제