问题
I want to get multiple result sets from a stored procedure using Entity Framework. Result of table get successfully, but when I want to get a Balance
column, it could not, any help will be appreciated.
Thanks
public ViewModel GetTwoResultSetsForUserId(string Date, string FromDate, string ToDate, int userId)
{
using (var db = new CuumiEntities())
{
// Create a SQL command and add parameter
var cmd = db.Database.Connection.CreateCommand();
cmd.CommandText = "getTransactionDatewisetesting";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Date", Date));
cmd.Parameters.Add(new SqlParameter("@FromDate", FromDate));
cmd.Parameters.Add(new SqlParameter("@ToDate", ToDate));
cmd.Parameters.Add(new SqlParameter("@UserId", userId));
// execute your command
db.Database.Connection.Open();
var reader = cmd.ExecuteReader();
double Balance = reader.GetDouble(0);
var transactions = ((IObjectContextAdapter)db)
.ObjectContext
.Translate<transaction>(reader)
.ToList();
reader.NextResult();
var Expenses = ((IObjectContextAdapter)db)
.ObjectContext
.Translate<spendingClass>(reader, "spendings", MergeOption.AppendOnly).ToList();
var balance = ((IObjectContextAdapter)db).ObjectContext.Translate<PrevBalance>(reader);
return new ViewModel
{
transactions = transactions,
Expenses = Expenses,
Balance = Balance
};
}
}
Here is my model which I want to return
and here is my stored procedure result:
回答1:
SQL Server and the .NET Framework are based on different type systems, that is why while reading data on .NET side you need to use data mapping carefully.
Here you can find list of type mapping or type equivalents between SQL Server and .NET Framework https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-data-type-mappings
In your question, it wasn't clear what was the type of Balance
column on SQL side or what type was coming from your stored procedure. In your code, you are trying to read Balance
column as Double
, that is where you are getting Specified cast is not valid in sql server
. According to Microsoft's document(link shared above), it is stated that column type must be Float
on SQL Server side so that on .NET side you can read it as Double
type.
As you are getting type cast error, I guess you are returning non Float
value from database. As a solution, you can update your stored procedure to cast your Balance
to Float
type.
Sample usage: SELECT CAST(Balance AS FLOAT)
Finally, just as a suggestion, wrap your Connection
and Reader
objects with using
statement so that at the end of your execution, they are disposed, not to leave open connections, which eventually can result in all pooled connections are in use exception.
来源:https://stackoverflow.com/questions/61839217/get-multiple-result-set-with-stored-procedure-using-entity-framework-calculated