Shankar
Shankar

Reputation: 1656

How to insert DateTime (or DateTime2) with Dapper?

I'm trying to do the following:

var p = new DynamicParameters();
p.Add(...);
p.Add(...);
// ideally I want to insert null for end date, but I also tried DateTime.MinValue
// or some other date, but doesn't help
p.Add("@endDate", null, DbType.DateTime, ParameterDirection.Input);
using (var con = new SqlConnection(ConnectionString))
{
    // stored procedure does 'select SCOPE_IDENTITY()' to return the id of inserted row.
    int id = con.Query<int>("StoredProcedureName", p, commandType: CommandType.StoredProcedure).First();
}

This is throwing "InvalidCastException" and I believe this is becase of the date. I previously had datetime2(20) for the endDate in the sql db, changed it to datetime to see if it fixes it, but doesn't. Can anyone help?

Upvotes: 3

Views: 2658

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063714

The invalid cast here is that SCOPE_IDENTITY() actually returns decimal. The parameters are working fine.

Upvotes: 2

Related Questions