C# 如何在实体框架 4 中处理 ObjectResult

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9654365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:20:25  来源:igfitidea点击:

How to handle ObjectResult in Entity Framework 4

c#entity-framework-4

提问by user1037747

In Entity Framework 4, I'm facing a problem when I use function import to a stored procedure and then using as a scalar value. It generates the code below:

在实体框架 4 中,当我将函数导入到存储过程然后用作标量值时,我遇到了问题。它生成以下代码:

public virtual ObjectResult<Nullable<int>> GetTopEmployee()
{
    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Nullable<int>("GetTopEmployee");
}

How do I use the return value of this method?

如何使用此方法的返回值?

For example, this code works fine:

例如,此代码工作正常:

NorthwindEntities db = new NorthwindEntities();
var i = db.GetTopEmployee();

But I want to use return values only as int. If I use return value as non while in function import it give -1 as output.

但我只想将返回值用作 int。如果我在函数导入时使用返回值作为非,它会给出 -1 作为输出。

When I try the code below:

当我尝试下面的代码时:

NorthwindEntities db2 = new NorthwindEntities();
int j = db.GetTopEmployee();

It throws an error saying:

它抛出一个错误说:

Cannot implicitly convert type 'System.Data.Objects.ObjectResult' to 'int'

无法将类型“System.Data.Objects.ObjectResult”隐式转换为“int”

How do I parse the above?

我如何解析以上内容?

采纳答案by Mike Two

Notice that the return type of GetTopEmployeeis an ObjectResult<Nullable<int>>. ObjectResult<T>implements IEnumerable<T>so your method is capable of returning more than one Nullable<int>.

请注意, 的返回类型GetTopEmployeeObjectResult<Nullable<int>>ObjectResult<T>实现,IEnumerable<T>因此您的方法能够返回多个Nullable<int>.

I assume you are trying to get some form of Id for the employee. If you are absolutely sure you are only going to get one result you could use the following code to get that Id.

我假设您正在尝试为员工获取某种形式的 Id。如果您绝对确定只会得到一个结果,则可以使用以下代码来获取该 ID。

  var topId = db.GetTopEmployee().FirstOrDefault();

topIdcould be null. You will have to use topId.Valueor var result = topId ?? -1;to get an int result.

topId可能为空。您将不得不使用topId.Valuevar result = topId ?? -1;获得 int 结果。

  NorthwindEntities db = new NorthwindEntities();
  int j = db.GetTopEmployee().FirstOrDefault() ?? -1;