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();
group
是Proxy
對象。
但是,如果我做context.Configuration.ProxyCreationEnabled = false;
或context.Configuration.LazyLoadingEnabled = false;
,那麼group
不是代理,但group.Users
爲空。
我該如何解決這個問題?
大!是工作!!!你能解釋我爲什麼嗎?謝謝。 – VansFannel
我已添加一些評論有幫助嗎? http://msdn.microsoft.com/en-us/library/vstudio/bb397933.aspx – Colin