Braveheart6M6
Braveheart6M6

Reputation: 81

How to pass a datetime parameter from Entity Framework SqlQuery and SqlParameter to a Stored Procedure?

This is my code on server:

model.Grid.DataSource =
       db.Database.SqlQuery<Reports.Cardex>("[dbo].[SP_RptCardexSummary_English_1] @OwnerCode, @TypeCode, @MeasurementUnitCode, @FDate",
       new SqlParameter { ParameterName = "@OwnerCode", Value = filterList[0] },
       new SqlParameter { ParameterName = "@TypeCode", Value = filterList[1] },
       new SqlParameter { ParameterName = "@MeasurementUnitCode", Value = filterList[2] },
       new SqlParameter { ParameterName = "@FDate", Value = filterList[3] })
       .ToList();

and my procedure:

ALTER PROCEDURE [dbo].[SP_RptCardexSummary_English_1] 

@OwnerCode int,
@TypeCode int,
@MeasurementUnitCode smallint,
@FDate datetime

UPDATE: I created a DateTime value by String:

var date = "2015/05/25";
var time = "20:30"
filterList.Add(Convert.ToDateTime(date + " " + time));

But when I pass a System.DateTime value, it throws an exception:

"The specified cast from a materialized 'System.DateTime' type to the 'System.String' type is not valid."

How should I pass it?
And interesting thing is, when I set SQL Profiler for observing and run what SQL Profiler received, It works fine!! What's the problem?

Upvotes: 1

Views: 2990

Answers (2)

Braveheart6M6
Braveheart6M6

Reputation: 81

Oops! I found out... ridiculously I forgot to change the type of one of my return data from string to Datetime!

Upvotes: 1

Shiraz Bhaiji
Shiraz Bhaiji

Reputation: 65431

There is a lot happening in this one line of code.

On the way down you are sending in a datetime to a datetime parameter.

The error message is a problem converting a date to a string. Could this be on the way up? Are you trying to send a date into a string on the datagrid?

You should start by creating a unit test that executes the stored procedure.

Upvotes: 0

Related Questions