8

我正在使用 asp mvc 3 应用程序。我有一个名为 History 的模型/实体。我有一个返回一个值的 linq 查询。根据我所做的,当调用该方法时,我会在控制器中收到“对象未设置为实例”错误,或者我会收到“无法从字符串隐式转换为 Models.History 类型”。所以我正在寻找解决问题的帮助,我只需要投射它还是什么?

这是给出“未设置对象”错误的方法:

public string GetPastAbuseData(int Id)
{

  var query = (from h in _DB.History
              where h.ApplicantId.Equals(Id)
              select h.AbuseComment).FirstOrDefault();

  return query.ToString();
 }

控制器:vm.HistoryModel.AbuseComment = repo.GetPastAbuseData(Id);

如果我将方法类型从字符串更改为历史记录,则会出现“无法转换”错误:

public History GetPastAbuseData(int Id)
{
    return (from h in _DB.History
            where h.ApplicantId.Equals(Id)
            select h.AbuseComment).SingleOrDefault();
}

感谢您的时间。

4

3 回答 3

13

您正在从 中选择AbuseComment属性(即字符串)HistoryObject。因此,您的代码尝试将字符串转换为History. 只需返回整个History实体:

public History GetPastAbuseData(int Id)
{
    return (from h in _DB.History
            where h.ApplicantId.Equals(Id)
            select h).SingleOrDefault();
}

同样在第一种情况下query将是字符串类型。你不需要调用ToString这个变量。更重要的是,当您陷入困境时OrDefault(),您将拥有NullReferenceException.

public string GetPastAbuseData(int Id)
{
  return (from h in _DB.History
          where h.ApplicantId.Equals(Id)
          select h.AbuseComment).FirstOrDefault();
}
于 2012-11-02T18:06:46.247 回答
5

你的第一个例子很好,你只需要检查空值。

public string GetPastAbuseData(int Id)
{

    var query = (from h in _DB.History
          where h.ApplicantId.Equals(Id)
          select h.AbuseComment).FirstOrDefault();

    return query == null ? string.empty : query;
 }
于 2012-11-02T18:24:46.620 回答
2

您可以使用 null 合并运算符,它将检查是否为 null,如果为 null,则返回 string.Empty。 ?? 操作员

public string GetPastAbuseData(int Id)
{
     return _DB.History.FirstOrDefault(h=>h.ApplicantId.Equals(Id)).Select(h=>h.AbuseComment) ?? string.Empty;
}
于 2012-11-02T18:49:25.273 回答