LINQ to Entities - 如何从实体返回单个字符串值

Bat*_*rog 7 c# linq asp.net-mvc linq-to-entities

我在asp mvc 3 app工作.我有一个名为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();
 }
Run Code Online (Sandbox Code Playgroud)

Controller: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();
}
Run Code Online (Sandbox Code Playgroud)

感谢您的时间.

Ser*_*kiy 12

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

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

在第一种情况下query也将是字符串类型.您不需要调用ToString此变量.更重要的是,当你OrDefault()遇到案件时,你会有NullReferenceException.

public string GetPastAbuseData(int Id)
{
  return (from h in _DB.History
          where h.ApplicantId.Equals(Id)
          select h.AbuseComment).FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)


小智 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;
 }
Run Code Online (Sandbox Code Playgroud)