2013-04-18 4 views
1

, 나는 기본적으로모델의 속성을 기반으로 쿼리하는 방법은 무엇입니까? 간결함을 위해서

public class Participant() 
{ 
    public int? ID {get; set;} 
    public string Name {get; set;} 
    public DateTime JoinDate {get; set;} 
    public string Address1 {get; set;} 
    public string City {get; set;} 
    public string County {get; set;} 
} 

public IList<Participant> SearchParticipants(Participant objParticipant) 
{ 
    using (Db.Context()) 
    { 
     //HOW CAN I ACHEIVE THIS? USING EF 
     //WARNING PSEUDO-CODE/MAGIC FUNCTION (SearchMatches) BELOW 

     return Db.Entities<Participant>().SearchMatches(objParticipant); 
    } 
} 

같은 참가자라는 이름의 모델을 가지고 가정, 나는 여러에게 .where(k => k.PropertyName) 쿼리를 구성하고 싶지 않아요. 나는 특정 PHP MVC 프레임 워크가 가지고 특정 속성을 가진 개체를 전달 생각 하나는 DB에서 일치하는 결과의 배열 (우리의 경우 IList) 가져옵니다.

+0

여러 어디에요 쿼리를 필요로하지 않을 한 당신 예를 들어 .Where (k => k.Prop1 == given.Prop1 && k.Prop2 == given.Prop2 ..)와 같이 일치시킬 속성을 지정하십시오. 이것을 대리자에 넣고 매개 변수로 보낼 수도 있습니다. –

+0

아마 반사와 동적 linq의 조합. 널 (또는 일부 "무시"값)이 아닌 객체의 속성을 반복하면서 동적 linq을 사용하여 where 절을 계속 추가합니다. –

+0

nullable 필드가 없기 때문에 무시할 필드와 사용할 필드를 어떻게 지정 하시겠습니까? –

답변

0

리플렉션을 사용하여 속성을 반복하고 dynamic linq을 사용하여 where 조건자를 작성할 수 있습니다.

다음은 출발점/개념 증명의 간단한 예입니다.

현재 우리가 where 절을 원하지 않는 것을 나타내는 값으로 null를 사용하지만, 당신이 값 형식 속성을 가지고있는 경우 (int를 같은) 당신은 [FilterIgnore]이나 뭐 같은 속성을 추가하고 확인할 수 있습니다 때 당신에게 루프가 속성을 통해.

다음 프로젝트에 샘플에서 동적 LINQ 파일을 추가 새 콘솔 응용 프로그램을 확인하고이 함께 program.cs을 바꿉니다하는,

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

class MyObject 
{ 
    // Some properties 
    public string PropertyA { get; set; } 
    public string PropertyB { get; set; } 
    public DateTime? PropertyC { get; set; } 

    static void Main(string[] args) 
    { 
     // Our repository 
     var list = new List<MyObject>() { 
       new MyObject() { PropertyA = "test"} , 
       new MyObject() { PropertyB = "test"} , 
       new MyObject() { PropertyC = DateTime.Today} , 
       new MyObject() { PropertyC = DateTime.Today, 
           PropertyA = "test"} 
      }; 

     // Loop through the filtered results 
     // (calling our GetByExample method with a 
     // new object with a property set) 
     foreach (var obj in 
       GetByExample(list, 
           new MyObject() { PropertyC = DateTime.Today })) 
     { 
      // Write some output so we can see it working 
      Console.WriteLine("Found object"); 
      Console.WriteLine(obj.PropertyA); 
      Console.WriteLine(obj.PropertyB); 
      Console.WriteLine(obj.PropertyC); 
     } 

     // Wait for the user to press a key before we close 
     Console.ReadKey(); 
    } 

    static IQueryable<MyObject> GetByExample(List<MyObject> objects, 
              MyObject filterObj) 
    { 
     // Create our query variable that we'll add to 
     var filteredObjects = objects.AsQueryable(); 

     // Loop through each property on this object 
     foreach (var prop in filterObj.GetType().GetProperties()) 
     { 
      // Get the value of this property 
      var propVal = prop.GetValue(filterObj, null); 

      if (propVal != null) 
      { 
       // If the property isn't null add a where clause 
       filteredObjects = 
        filteredObjects.Where(string.Format("{0} = @0", 
                 prop.Name), 
              propVal); 
      } 
     } 

     return filteredObjects; 
    } 
} 
+0

'filteredObjects = filterObjects.Where ("{0} = @ 0", prop.Name), propVal);'에 컴파일 오류가 발생했습니다. 수정 방법을 알 수 없습니다. –

+0

다운로드하여 동적 linq 귀하의 프로젝트에. –

+0

감사합니다 George! 다이나믹 Linq는 확실히 게임 체인저로 보인다. 불쌍한 점이 E.F 5.0에 내장되어 있지 않습니다. (또는 그랬습니까?) –

관련 문제