Reputation: 403
I'm building an API for basic CRUD operations on a database table. I'm using C# in an ASP.NET Web API project and my service classes live in a separate class library. Dapper and Dapper.SimpleCRUD used for ORM operations.
When I hard code a guid into the database using DEFAULT NEWID()
, my create methods work fine. But for best practice I want to create a new guid in the controller class and then send it to the DB. When I do this it fails.
In the Controller:
var newParty = new Party()
{
Id = Guid.NewGuid(), //this is when I started getting the cast error
Name = party.Name,
CreatedDate = DateTime.Now
};
In the repository:
public int? Create(Party obj)
{
using (var connection = new SqlConnection(_connectionString))
{
connection.Open();
var result = connection.Insert(obj);
return result;
}
}
I get an "Unable to cast object of type 'System.Guid' to type 'System.IConvertible'."
response.
Here is the stack trace:
at System.Convert.ToInt64(Object value)\r\n at Dapper.SimpleCRUD.Insert[TKey](IDbConnection connection, Object entityToInsert, IDbTransaction transaction, Nullable`1 commandTimeout) in C:\\Users\\ecoffman\\Documents\\GitHub\\Dapper.SimpleCRUD\\Dapper.SimpleCRUD\\SimpleCRUD.cs:line 364\r\n at KC.QMS.CrudRepository`1.Create(T obj) in D:\\Isoright\\src\\WebApp\\KC.QMS\\CrudRepository.cs:line 86\r\n at KC.QMS.Services.InterestedPartyService.CreateInterestedParty(InterestedParty interestedParty) in D:\\Isoright\\src\\WebApp\\KC.QMS\\Services\\InterestedPartyService.cs:line 27\r\n at IsoRight.Api.Controllers.InterestedPartyController.CreateInterestedParty(InterestedParty interestedParty) in D:\\Isoright\\src\\Api\\IsoRight.Api\\Controllers\\InterestedPartyController.cs:line 73
Upvotes: -1
Views: 2481
Reputation: 11289
The generic Insert method is designed for int primary keys. You can pass in the type as the first parameter. Here is an example:
connection.Insert<Guid, T>;
See the unit tests for this here: hhttps://github.com/ericdc1/Dapper.SimpleCRUD/blob/master/Dapper.SimpleCRUDTests/Tests.cs#L682
Upvotes: 1