Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
784 views
in Technique[技术] by (71.8m points)

c# - How to handle ObjectResult in Entity Framework 4

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:

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.

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'

How do I parse the above?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Notice that the return type of GetTopEmployee is an ObjectResult<Nullable<int>>. ObjectResult<T> implements IEnumerable<T> so your method is capable of returning more than one 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.

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

topId could be null. You will have to use topId.Value or var result = topId ?? -1; to get an int result.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...