我正在使用Entity Framework Code First 4.4.0.0库,C#和.NET Framework 4.0开发WCF RESTful服务。
我正在尝试使用此方法检索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
为空。
如何解决此问题?
答案 0 :(得分: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
除非您打算稍后访问该数据,否则不需要包含