4

I'm wanting to call this stored procedure with input parameters:

proc [dbo].[Invoice_GetHomePageInvoices] (

      @FinancialYearStartDate datetime = null
,      @FinancialYearEndDate datetime = null

Trouble with this is the way I usually call a stored proc from my code is:

return _db.Database.SqlQuery<HomePageInvoice>(string.Format("EXEC Invoice_GetHomePageInvoices @FinancialYearStartDate = '{0}', @FinancialYearEndDate = '{1}'", financialYear.StartDate.ToString(), financialYear.EndDate.ToString()));

So this isn't going to work because I've basically converted my datetimes to strings.

How the heck am I supposed to do this?

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
AnonyMouse
  • 18,108
  • 26
  • 79
  • 131

2 Answers2

6

You should use sql parameters, basically like this:

var startDate = new SqlParameter("FinancialYearStartDate", dateTimeValueHere);
var endDate = new SqlParameter("FinancialYearEndDate", dateTimeValueHere);

return _db.Database.SqlQuery<HomePageInvoice>("Invoice_GetHomePageInvoices", startDate, endDate);

More info: How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5

Community
  • 1
  • 1
Ropstah
  • 17,538
  • 24
  • 120
  • 194
0
  1. convert the date to a string with specific format.
  2. use SQL code to convert it back to an sql datetime object.

When using sql server (microsoft): http://msdn.microsoft.com/en-us/library/ms187928.aspx "convert(datetime, '{0}', 103)", financialYear.EndDate.ToString("MM/dd/yyyy")

edit: Ropstah's method is actually better, this is just the way I used to do it :P

MrFox
  • 4,852
  • 7
  • 45
  • 81