-1

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
Ryan
  • 393
  • 7
  • 22
  • 1
    https://github.com/ericdc1/Dapper.SimpleCRUD/issues/97 (found by Googling for `SimpleCRUD GUID System.IConvertible`) – mjwills Jun 04 '19 at 08:48
  • To be honest - this library is unreliable and quite buggy. It's much easier to write your own simple DAL with Dapper – Fabjan Jun 04 '19 at 08:48
  • 1
    Yes it did thanks @mjwills. I couldn't solve it alone. Took a bit of tweaking from a more senior dev due to the complexity of the code in the service class. But thanks for the help! – Ryan Jun 19 '19 at 16:45

1 Answers1

1

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

ericdc
  • 11,217
  • 4
  • 26
  • 34