Chakavak Behzad
Chakavak Behzad

Reputation: 807

How convert a stored procedure result to a specific type

I have a stored procedure in SQL Server and convert it to a function in my Entity Model, now how can I convert the output of my function to a given type in C# such int,string and so on?

Example:

Testentities test=new TestEntities();
object d=test.FunctionTest("Params");

Upvotes: 1

Views: 4203

Answers (1)

marc_s
marc_s

Reputation: 754458

To a string:

Testentities test = new TestEntities();
object d = test.FunctionTest("Params");
string result = d.ToString();

To int:

Testentities test = new TestEntities();
object d = test.FunctionTest("Params");
int result = Convert.ToInt32(d);

The .NET Convert class can convert to a lot of different types.

But a word of caution: of course you need to be certain that the target type is the right type, and even then - you need to be prepared for the fact the conversion might fail - put this in a try...catch block!

Update: after you've revealed that the result is in fact a List<object>, you need to do something like:

Testentities test = new TestEntities();
object d = test.FunctionTest("Params");

List<string> results = new List<string>();

foreach(object o in d)
{
    results.Add(o.ToString());
}

and the same can be done with the int values (just use Convert.ToInt32() in the foreach loop

Upvotes: 1

Related Questions