我有這樣的代碼,運行正常:從Linq到列表使用擴展方法
//我的控制器
public HttpResponseMessage GetUserFavorites(string id)
{
var response = Request.CreateResponse();
response.Content = new StringContent(JsonConvert.SerializeObject(jobRepository.GetUserFavorites(id)));
response.StatusCode = HttpStatusCode.OK;
return response;
}
//我jobRepository
public IQueryable<ProfileInfo> GetUserFavorites(string iUserId)
{
var profiles = from favoriate in db.TB_Res_Favorites
join profile in db.TB_Res_Profile on favoriate.ProfileID equals profile.ProfileID
where favoriate.UserId == iUserId
select new ProfileInfo()
{
ProfileID = profile.ProfileID,
FullName = profile.FullName,
Headline = profile.Headline,
Location = profile.Location,
Industry = profile.Industry,
ImageUrl = profile.ImageUrl,
EducationInstitute = profile.EducationInstitute,
Degree = profile.Degree
};
return profiles;
}
的問題是,該映射到ProfileInfo
將在我的代碼中的許多地方返回。我顯然想避免這種情況。我想用擴展方法,將從EF映射到我的課是這樣的:
//我的分機:
public static class ModelExtensions
{
public static ProfileInfo ToProfileInfo(this TB_Res_Profile dbProfile)
{
return new ProfileInfo
{
ProfileID= dbProfile.ProfileID,
FullName = dbProfile.FullName,
Headline = dbProfile.Headline,
Location = dbProfile.Location,
Industry = dbProfile.Industry,
ImageUrl = dbProfile.ImageUrl,
EducationInstitute = dbProfile.EducationInstitute,
Degree = dbProfile.Degree
};
}
}
,並使用它像這樣(CONTROLER不變):
public IQueryable<ProfileInfo> GetUserFavorites(string iUserId)
{
var profiles = from favoriate in db.TB_Res_Favorites
join profile in db.TB_Res_Profile on favoriate.ProfileID equals profile.ProfileID
where favoriate.UserId == iUserId
select profile.ToProfileInfo();
return profiles;
}
是編譯好的,但我得到這個錯誤在運行時間:
「System.NotSupportedException」類型的異常出現在
Newtonsoft.Json.dll
但在用戶代碼中沒有處理其他信息:
LINQ
到實體無法識別 方法「myApp.Models.InfoClass.ProfileInfo ToProfileInfo(myApp.Models.TB_Res_Profile)」方法,和該方法 不能被翻譯成商店表達。
我知道有我可以使用的自動映射器。但是真的讓我感興趣做這項工作,並明白這裏有什麼問題。
謝謝你,我會用你的答案,小評論:在擴展它應該是xProfileID insPDBProfile.ProfileID等等。 – Ilan 2015-02-08 11:28:56
這就是爲什麼複製/粘貼是邪惡的。謝謝,我已經更新了答案。 – 2015-02-08 11:34:47