2012-11-09 4 views
1

테이블의 이름과 조회 할 특정 열의 값을 취하는 부분 결과보기가 있습니다. DBContext API를 읽고 Set (Type)이 CRUD 작업을 수행 할 수있는 DBSet을 반환해야한다는 것을 알았습니다. 사용자가 PK를 알지 못하기 때문에 PK없이 DBSet을 쿼리하는 방법을 정확히 모릅니다.동적 DBSet 조회 및 쿼리

클래식 ADO를 사용하면 더 쉬워 질까요?

편집 : DbSet.SQLQuery 함수를 사용하는 방법을 알아 냈지만 결과를 저장할 단서가 없습니다. 디버거에서 요소를 검사하고 테이블 내의 모든 행을 찾은 SQLQuery가 작동합니다.

public class SF1DB : DbContext 
{ 
    //List of table names that feeds a DropDownList 
    public DbSet<tablelist> tables { get; set; } 

    //Data table 
    public DbSet<dataTable1> dataTable1 { get; set; } 
    public DbSet<dataTable2> dataTable2 { get; set; } 
    //...list of other tables 
} 

public PartialViewResult GetFeatures(String tablelist, String[] countyfp) 
{ 
    String type = "MvcApplication1.Models." + tablelist; 
    Type dbType = Type.GetType(type); 
    DbSet set = _db.Set(dbType); 
    String sql = "select * from " + tablelist; 

    //How do I store the result in a variable? 
    set.SqlQuery(sql); 
    return PartialView(); 
} 
+0

동적으로 설정하지 않으려는 경우의 예를 제공 할 수 있습니까? – barry

+0

40 if 문을 사용하여 사용자가 쿼리 할 테이블을 확인한 다음 DbContext를 통해 쿼리 할 수 ​​있습니다. – MooCow

답변

0

사용자가 선택한 DbSet과 동일한 유형의 목록을 만들어서 알아 냈습니다. 그런 다음 SQLQuery의 GetEnumerator 메서드를 사용하여 결과를 반복하고 새 목록에 추가합니다. 마지막으로 부분보기로 목록을 전달하십시오.

public PartialViewResult GetFeatures(String tablelist, String[] countyfp) 
{ 
    String type = "MvcApplication1.Models." + tablelist; 
    Type dbType = Type.GetType(type); 
    DbSet set = _db.Set(dbType); 
    String sql = "select * from " + tablelist + " where "; 
    Type listType = typeof(List<>).MakeGenericType(dbType); 
    IList list = (IList)Activator.CreateInstance(listType); 

    for (int i = 0; i < countyfp.Length; i++) 
    { 
     sql += "cntyidfp like '%" + countyfp[i] + "'"; 
     if (i < (countyfp.Length - 1)) 
     { 
      sql += " or "; 
     } 
    } 

    IEnumerator result = set.SqlQuery(sql).GetEnumerator(); 
    while (result.MoveNext()) 
    { 
     list.Add(result.Current);     
    } 

    return PartialView(list); 
}