2013-11-12 4 views
0

C# 및 .NET Framework 4.0을 사용하여 Entity Framework Code First 4.4.0.0 라이브러리를 개발 중입니다.Entity Framework에서 IQueryable 실행

어떻게 where 절에 배열을 사용하여 쿼리를 동적으로 만들 수 있습니까? 그리고 내가 발견 한이 (here) :

IQueryable<Product> SearchProducts (params string[] keywords) 
{ 
    IQueryable<Product> query = dataContext.Products; 

    foreach (string keyword in keywords) 
    { 
    string temp = keyword; 
    query = query.Where (p => p.Description.Contains (temp)); 
    } 
    return query; 
} 

하지만 그것을 사용하는 방법을 모르겠어요. 어떻게이 쿼리를 실행할 수 있습니까?

using (var context = new MyContext()) 
{ 
    context.Configuration.ProxyCreationEnabled = false; 

    var users = from u in context.Users.Include("WhoHasBlockedMe").Include("Friends") 
       from act in u.WantsToDo 
       where act.ActivityId == activityId && 
        u.Gender == genderId && 
        u.City == city && 
        u.Country == countryIsoCode 
       select u; 

    // This user doesn't exit on database 
    if ((users == null) || 
     (users.Count() == 0)) 
    { 
     ctx.StatusCode = System.Net.HttpStatusCode.NotFound; 
     ctx.SuppressEntityBody = true; 
    } 
    else 
    { 
     usersList = new List<UserProfile>(); 
     foreach(User us in users.ToList()) 
     { 
      usersList.Add(UserProfile.CreateUserView(us, userId)); 
     } 
     ctx.StatusCode = System.Net.HttpStatusCode.OK; 
    } 
} 

가 어떻게 해당 쿼리를 실행할 수 있습니다

나는 보통 이렇게?

답변

1

당신은 당신의 쿼리를 실행하고 결과를 얻을해야합니다

query.ToList() 

당신의 예제에서는 다음과 같은 모습이 될 것입니다 :

var users = SearchProducts().ToList(); 
if ((users == null) || (users.Count() == 0)) 
{ 
    ctx.StatusCode = System.Net.HttpStatusCode.NotFound; 
    ctx.SuppressEntityBody = true; 
} 
else 
{ 
    usersList = new List<UserProfile>(); 
    foreach(User us in users) 
    { 
     usersList.Add(UserProfile.CreateUserView(us, userId)); 
    } 
    ctx.StatusCode = System.Net.HttpStatusCode.OK; 
} 
+0

답변 주셔서 감사 많이. – VansFannel

관련 문제