我是mvc的新手,我遇到了以下代码的问题,它抛出异常:
LINQ to Entities无法识别方法'System.String ToString(System.DateTime)'
方法,并且此方法无法转换为存储表达式。
public ActionResult JobSearchList(PostJobModel model)
{
try
{
if (Session["USER_ID"] != null)
{
var subscriber_Id = RL_Constants.RES_ID;
var company_Id = RL_Constants.COMP_ID;
var resource_Typa = RL_Constants.RES_TYPE;
var jobPostDetails = (from jobPost in reslandentity.JOB_POSTING
where jobPost.COMP_ID == RL_Constants.COMP_ID
select new PostJobModel
{
POST_DT=Convert.ToString(jobPost.POST_DT),
POST_END_DT=Convert.ToString(jobPost.POST_END_DT),
POSITIONS_CNTS=Convert.ToString(jobPost.POSITIONS_CNT),
JOB_TYPE = jobPost.JOB_TYPE,
SKILLS = jobPost.SKILLS,
DURATION = jobPost.DURATION,
CATEGORY=jobPost.CATEGORY,
PREREQUISITES = jobPost.PREREQUISITES,
LOCATION=jobPost.LOCATION,
RATE=jobPost.RATE,
PERKS = jobPost.PERKS,
CONTACT_PERSON=jobPost.CONTACT_NAME,
CONTACT_EMAIL=jobPost.CONTACT_INFO,
CONTACT_PHONE=jobPost.CONTACT_INFO,
POST_TITLE=jobPost.TITLE,
DESCRIPTION=jobPost.DESCR
}).ToList();
model.GetJobPostDetails = jobPostDetails;
}
return View(model);
}
catch (Exception ex)
{
throw ex;
}
}
答案 0 :(得分:1)
错误非常自我解释,LINQ提供程序不支持ToString
,因此您无法在查询中使用它。
下拉原始数据并在内存中执行转换。
var jobPostDetails = reslandentity.JOB_POSTING
.Where(x => x.COMP_ID == RL_Constants.COMP_ID)
.AsEnumerable() // materialize query, Select will be performed in memory
.Select(x => new {
POST_DT = x.POST_DT.ToString(),
POST_END_DT = x.POST_END_DT.ToString(),
POSITIONS_CNTS = x.POSITIONS_CNT.ToString(),
...
})
.ToList();
AsEnumerable
会将上下文从IQueryable<T>
切换到IEnumerable<T>
,因此允许在查询中调用特定于CLI的方法。在调用 ToList
之后,查询仍然只会实现,因为AsEnumerable
会保留延迟执行。
答案 1 :(得分:1)
在尝试转换内部 LINQ查询时,请查看SqlFunctions。
SqlFunctions.DateName("dd", jobPost.POST_DT) +
SqlFunctions.DateName("mm", jobPost.POST_DT) +
SqlFunctions.DateName("yyyy", jobPost.POST_DT) +
此函数也可以在where子句等中使用。