我在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();
}
感谢您的时间。
答案 0 :(得分:11)
您正在从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();
}
答案 1 :(得分:4)
你的第一个例子很好,你只需要检查是否为空。
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;
}
答案 2 :(得分:2)
您可以使用null coalescing运算符来检查是否为null,如果为null则返回string.Empty。 ?? Operator
public string GetPastAbuseData(int Id)
{
return _DB.History.FirstOrDefault(h=>h.ApplicantId.Equals(Id)).Select(h=>h.AbuseComment) ?? string.Empty;
}