LINQ上没有记录的例外情况

时间:2016-01-24 17:43:47

标签: c# entity-framework linq

我的实体课程是:

public class JobChatMessage : BaseEntity
{
    public string Text { get; set; }
    public Job Job { get; set; }
    public ApplicationUser Sender { get; set; }
}

public class Job : BaseEntity
{
    public string Title { get; set; }
    public DateTime PostingDate { get; set; }
    public ApplicationUser CreatedBy { get; set; }
    public List<Comment> Comments { get; set; }
}

当数据库中没有记录时,下面的LINQ会出现异常:无法创建类型的常量值。在此上下文中仅支持原始类型或枚举类型。

public async Task<IHttpActionResult> GetJobChatMessages(long jobId, string email)
{
    var user = db.Users.Where(x => x.UserName == email).First();
    var job = db.Jobs.Find(jobId);
    try
    {
        var query = db.JobChatMessages.Where(x => x.Job == job);
        var temp = await query.ToListAsync(); // <-- exception here
        var result = temp.Select(...); // convert the results.

        return Ok(new { success = true, data = result });
    }
    catch (Exception ex)
    {
        return InternalServerError();
    }
}

任何人都可以帮助我吗?或者我如何改变这个查询,以便即使DB中没有记录也不会发生异常

0 个答案:

没有答案