Search code examples
.netentity-frameworkdatetimesqlparameter

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?


Solution

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