2017-11-13 19 views
0

Entity Framework 및 LINQ를 사용하고 있습니다. GridViews의 "도우미"클래스에서 재사용 가능한 메서드를 만들고 싶습니다.스위치를 사용하지 않고 GetType()에서 파생 된 형식 사용

이 메서드는 전달 된 엔터티 형식을 기반으로 엔터티 목록으로 DataSource를 반환합니다. 나는 내가 제안을 열어 오전 방법의 문자열로 원하는 개체 유형을 통과해야하는 경우

GridView1.DataSource = helperClass.GetDataSource(new Entity1()); 

참고 * : 호출이 같이 있도록

그래서 GridView1은의 [Entity1]이 표시됩니다. 난 그냥이 방법은

는 재사용 방법은 간단합니다 반환 및 유사 수있는 ~ 40 개체 타입 사이에 스위치 케이스를 사용하고 싶지 않습니다

public static object GetDataSource(object type) 
{ 
    using (DatabaseContext dc = new DatabaseContext()) 
    { 
     if (dc.[how do I get the entity type here].Count() > 0) 
     { 
      var modelList = dc.[how do I get the entity type here also].ToList(); 
     } 
    } 
} 

이 바보 같은 소리, 하지만 분명히 할 수 없었습니다.

var modelList = dc.(type.GetType()).ToList(); 

하지만 기본적으로 달성하고자하는 것입니다. 당신이 컴파일 타임에 유형을 결합 할 경우

+0

무슨 소용이 당신입니까? 객체 목록을 얻지 만 컴파일 타임에 객체 유형을 알지 못합니까? 나는 제네릭으로 원하는 것을 할 수있는 더 나은 방법이 있다고 생각합니다. –

+0

말하자면, 이것은 https://stackoverflow.com/questions/1919632의 복제본에 가깝습니다. 차이점은 먼저 유형에서 이름을 가져와야한다는 것입니다. –

+0

@DStanley 잘 될지도 모릅니다. 이것은 재사용 가능한 도우미 메서드를 만들 때 생각한 첫 번째 방법이었습니다. 비슷한 메소드 (sort, bind, databound와 같은)를 가진 다중 GridView가있는 웹 애플리케이션이 있으므로 동일한 코드를 입력하는 대신 원격 메소드에서 재사용 가능한 메소드를 만들고 싶었습니다. GridView) ~ 40 times – toadfromgrove

답변

0

, 당신은 일반적인 인수로 유형을 통과 및 방법 이런 종류의 사용할 수 있습니다

 public DbSet<T> GetDataSource<T>() 
     { 
      var targetType = typeof(DbSet<T>); 

      return _db 
       .GetType() 
       .GetMethods() 
       .Where(m => m.ReturnType == targetType) 
       .Single() 
       .Invoke(_db, null) as DbSet<T>; 
     } 

는 어떻게 작동합니까를? 요청 된 엔티티를 반환하는 메소드의 이름을 알 수는 없지만 반환 유형은 DbSet<T>이어야합니다. 그래서 우리는 DatabaseContext를 스캔하여 그 타입을 반환하는 메소드를 찾고 호출합니다. 여기에는 반환 유형이있는 메서드가 하나만 있다고 가정합니다.

실제 런타임 바인딩이 필요하면 (<T> 매개 변수를 제공 할 수 없음)이 방법을 사용할 수 있습니다. 반환 형식은 컴파일시 알 수없는 경우 특정 반환 형식을 사용할 수 없기 때문에 일반용 IEnumerable입니다. 필요한 경우 언제든지 DbSet<T>으로 다시 전송할 수 있습니다.

 public IEnumerable GetDataSource(Type type) 
     { 
      var targetType = typeof(DbSet<>).MakeGenericType(new Type[] { type }); 

      return _db 
       .GetType() 
       .GetMethods() 
       .Where(m => m.ReturnType == targetType) 
       .Single() 
       .Invoke(_db, null) as IEnumerable; 
     } 

다음은 전체 예제입니다. EF 객체를 스텁 했는데도이 예제는 여전히 DbSetDatabaseContext으로 작동해야합니다.

using System; 
using System.Linq; 
using System.Collections; 
using System.Collections.Generic; 

public class Program 
{ 

    public class DbSet<T> : List<T> 
    { 
    } 

    public class User 
    { 
     public string Name { get; set; } 
     public override string ToString() 
     { 
      return "User " + Name; 
     } 
    } 

    public class Transaction 
    { 
     public decimal Amount { get; set; } 
     public override string ToString() 
     { 
      return "Transaction " + Amount.ToString("0.00"); 
     } 
    } 

    public class DatabaseContext 
    { 
     public DbSet<User> GetUsers() 
     { 
      return new DbSet<User>() 
      { 
       new User { Name = "Bob" }, 
       new User { Name = "Alice" } 
      }; 
     } 
     public DbSet<Transaction> GetTransactions() 
     { 
      return new DbSet<Transaction>() 
      { 
       new Transaction { Amount = 12.34M }, 
       new Transaction { Amount = 56.78M } 
      }; 
     } 

    } 

    public class HelperClass 
    { 
     private readonly DatabaseContext _db; 

     public HelperClass(DatabaseContext db) 
     { 
      _db = db; 
     } 

     public DbSet<T> GetDataSource<T>() 
     { 
      var targetType = typeof(DbSet<T>); 

      return _db 
       .GetType() 
       .GetMethods() 
       .Where(m => m.ReturnType == targetType) 
       .Single() 
       .Invoke(_db, null) as DbSet<T>; 
     } 

     public IEnumerable GetDataSource(Type type) 
     { 
      var targetType = typeof(DbSet<>).MakeGenericType(new Type[] { type }); 

      return _db 
       .GetType() 
       .GetMethods() 
       .Where(m => m.ReturnType == targetType) 
       .Single() 
       .Invoke(_db, null) as IEnumerable; 
     } 
    } 

    public static void Main() 
    { 
     var helperClass = new HelperClass(new DatabaseContext()); 

     foreach (var u in helperClass.GetDataSource<User>()) 
     { 
      Console.WriteLine(u); 
     } 

     foreach (var t in helperClass.GetDataSource(typeof(Transaction))) 
     { 
      Console.WriteLine(t); 
     } 

    } 
} 

출력 :

User Bob 
User Alice 
Transaction 12.34 
Transaction 56.78 

Full code on DotNetFiddle