我不找任何一個解決的稱號,我尋求建議純屬提到的問題,因爲我有固定的我自己但我想得到一些專家的意見,我有一個方法,加載用戶的詳細信息並返回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