Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 935
Shankar Avatar asked Apr 29 '26 13:04

Shankar


1 Answers

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

like image 115
Marc Gravell Avatar answered May 01 '26 02:05

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!