我不找任何一个解决的称号,我寻求建议纯属提到的问题,因为我有固定的我自己但我想得到一些专家的意见,我有一个方法,加载用户的详细信息并返回UserProfile()类实体或复杂类型“WebServices.UserProfile”不能在LINQ构建以查询实体
如下图所示,运行与下面的代码的应用程序时的关键点我得到上述错误。
public UserProfile LoadUserDetails(Int64 userId)
{
var userProfile = new UserProfile();
using (var context = new Context())
{
userProfile = (from p in context.UserProfile
where p.UserId == userId
select new UserProfile()
{
UserId = userId,
Firstname = p.Firstname,
Surname = p.Surname,
Username = p.Username,
CurrentlyOnline = p.CurrentlyOnline,
JoinedDate = p.JoinedDate,
UserLocation = p.UserLocation
}).FirstOrDefault();
context.Dispose();
}
return userProfile;
}
如果我添加.AsEnumerable()它的工作原理如下图所示
public UserProfile LoadUserDetails(Int64 userId)
{
var userProfile = new UserProfile();
using (var context = new Context())
{
userProfile = (from p in context.UserProfile.AsEnumerable()
where p.UserId == userId
select new UserProfile()
{
UserId = userId,
Firstname = p.Firstname,
Surname = p.Surname,
Username = p.Username,
CurrentlyOnline = p.CurrentlyOnline,
JoinedDate = p.JoinedDate,
UserLocation = p.UserLocation
}).FirstOrDefault();
context.Dispose();
}
return userProfile;
}
现在,当上面提到我用下面的代码固定的错误,纯粹是因为每一个解决方案,我看了更适合于这种方法,我将用户加载到临时类中,创建UserProfile()的新实例并从临时类中填充相关变量。
public UserProfile LoadUserDetails(Int64 userId)
{
var userProfile = new UserProfile();
using (var context = new Context())
{
var t = (from p in context.UserProfile
where p.UserId == userId
select new
{
UserId = userId,
Firstname = p.Firstname,
Surname = p.Surname,
Username = p.Username,
CurrentlyOnline = p.CurrentlyOnline,
JoinedDate = p.JoinedDate,
UserLocation = p.UserLocation
}).FirstOrDefault();
userProfile = new UserProfile
{
UserId = userId,
Firstname = t.Firstname,
Surname = t.Surname,
Username = t.Username,
CurrentlyOnline = t.CurrentlyOnline,
UserLocation = t.UserLocation,
JoinedDate = t.JoinedDate
};
context.Dispose();
}
return userProfile;
}
所以我给你的问题是什么是最好的方法代码示例2或3?考虑性能。
我正在学习实体框架6所以最好我想正确地使用它。
谢谢
好吧,我想我会扩展到只返回我需要的7个字段,因为我并不需要UserProfile中的所有15列,并且从我教过的内容中只选择需要帮助的性能列。 – 2014-10-30 10:49:29
作为一般指导原则,只有选择你需要的东西。但是如果你从表中选择一行,我认为你获得的表现相当不错。另一方面,如果你用这个查询方法调用数百万次... – Maarten 2014-10-30 10:51:00
这就是我想要解决的问题,因为我可以让5000多个用户打这个应用程序,所以我非常理想并试图实现一个合适的方法,因为我想要的最后一件事是应用程序停下来。 – 2014-10-30 10:57:19