2013-04-26 1 views
1

나는 asp.net mvc3에서 일하고있다.EntityFramework - ObjectSet을 얻는 방법 <T>

ADO.NET 엔터티 데이터 모델로 만든 edmx가 있습니다. (데이터-처음으로)

TestDb.Designer.cs

namespace Test.Web.DataModel 
{ 
    public partial class TestDbContext : ObjectContext 
    { 
     public ObjectSet<T_Members> T_Members { ... } 
     public ObjectSet<T_Documents> T_Documents { ... } 
     .... 
    } 
} 

어떻게 이름 (문자열)에 의해 ObjectSet를 얻으려면?

예를 들어, 나는 이것을 원합니다.

var members = context.GetTable("T_Members"); // var members = context.T_Members; 

답변

2

나는 ObjectContext 내부와 그 익숙하지 않은, 그래서 더 '기본'방법,

가있을 수 있습니다 ...하지만 당신이 필요로하는 일부 reflection이 당신의 재산을 얻는 것입니다.
(참고 : 나는하지 않는 DB-먼저 일부 오타 경우 조정해야 할 것이다, 그래서 확인하기 편리합니다 -하지만 작동합니다)

public static object GetTableFromName(this TestDbContext db, string propertyName) 
{ 
    PropertyInfo property = null; 
    property = typeof(TestDbContext) 
     .GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public); 
    return property.GetValue(db, null); 
} 
public static object GetTableFromType(this TestDbContext db, string tableTypeName) 
{ 
    // var tableType = typeof(TestDbContext).Assembly.GetType("YourNamespace.T_Members"); 
    var tableType = Type.GetType(tableTypeName); 
    var genericType = typeof(ObjectSet<>).MakeGenericType(new[] { tableType }); 
    var property = typeof(TestDbContext) 
     .GetProperties(BindingFlags.Instance | BindingFlags.Public) 
     .Where(x => x.PropertyType == genericType).FirstOrDefault(); 
    return property.GetValue(db, null); 
} 

var table = db.GetTableFromName("T_Members"); 
table = db.GetTableFromType("YourNamespace.T_Members); 
// this gets you the `object` you'd still need to 'cast' or something 
+0

처럼 사용 감사합니다. – isnotnull

+0

@ 최종환 당신은 이것을 다음과 같이 표시해야합니다 - 환영합니다. 도움이 되었기 때문에 기쁩니다. – NSGaga

관련 문제