2013-11-21 219 views
0

我正在開發一個WCF RESTful服務,使用實體框架代碼優先4.4.0.0庫,C#和.NET Framework 4.0。WCF和實體框架代理對象

我試圖找回組,其中user_id是用這種方法成員:

public List<Group> GetUserGroups(string user_id) 
{ 
    List<Group> groups = null; 
    int userId; 
    OutgoingWebResponseContext ctx = 
     WebOperationContext.Current.OutgoingResponse; 

    // Check parameters. It will throw an exception. 
    ParameterCheck.CheckObjectId(user_id); 

    // Parase parameter to int. 
    userId = Int32.Parse(user_id); 

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

      User user = context.Users.Find(userId); 

      if (user == null) 
      { 
       ThrowCustomWebException(
        (int)ExceptionReasons.InvalidUser, 
        (int)ExceptionDetailedInformation.UserNotFound); 
      } 
      else 
      { 
       var grps = from g in context.Groups.Include("Users").Include("WantsToDo") 
          from u in g.Users 
          where u.UserId == userId 
          select g; 

       if ((grps == null) || 
        (grps.Count() == 0)) 
       { 
        ctx.StatusCode = System.Net.HttpStatusCode.NotFound; 
        ctx.SuppressEntityBody = true; 
       } 
       else 
       { 
        foreach (Group group in grps) 
        { 
         group.UsersIds = group.Users.Select(u => u.UserId).ToList(); 
         group.ActivityIds = group.WantsToDo.Select(a => a.ActivityId).ToList(); 
        } 
        groups = grps.ToList(); 

        ctx.StatusCode = System.Net.HttpStatusCode.OK; 
       } 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     // ReThrow this exception because we need to indicate that the user is 
     // invalid because there isn't that user on database. 
     if ((ex is WebFaultException<ErrorData>)) 
      throw; 
     else 
     { 
      TraceTool.WriteTraceLog(ex, "GetUserGroups"); 

      ctx.StatusCode = System.Net.HttpStatusCode.InternalServerError; 
      ctx.SuppressEntityBody = true; 
     } 
    } 

    return groups; 
} 

但是,我有一個問題,因爲WCF,在這裏:

group.UsersIds = group.Users.Select(u => u.UserId).ToList(); 

groupProxy對象。

但是,如果我做context.Configuration.ProxyCreationEnabled = false;context.Configuration.LazyLoadingEnabled = false;,那麼group不是代理,但group.Users爲空。

我該如何解決這個問題?

回答

3

試試這個:

var groups = from g in context.Groups   //Get all Groups in the database 
           .Include("Users") //Get the User data too 
           .Include("WantsToDo") //Get the WantsToDo data too 
where g.Users.Any(u => u.UserId == user_id) //Only get groups where the user_id 
              //is in Users collection 
select g 

你並不需要包括除非你打算訪問這些數據後

+0

大!是工作!!!你能解釋我爲什麼嗎?謝謝。 – VansFannel

+0

我已添加一些評論有幫助嗎? http://msdn.microsoft.com/en-us/library/vstudio/bb397933.aspx – Colin