我正在为数据库表上的基本CRUD操作构建一个API。我在一个ASP.NET Web API项目中使用C#,我的服务类位于一个单独的类库中。用于对象关系管理操作的Dapper和Dapper.SimpleCRUD。
当我使用DEFAULT NEWID()将guid硬编码到数据库中时,我的create方法工作得很好。但作为最佳实践,我想在控制器类中创建一个新的guid,然后将其发送到DB。当我这样做的时候,它失败了。
在控制器中:
var newParty = new Party()
{
Id = Guid.NewGuid(), //this is when I started getting the cast error
Name = party.Name,
CreatedDate = DateTime.Now
};在存储库中:
public int? Create(Party obj)
{
using (var connection = new SqlConnection(_connectionString))
{
connection.Open();
var result = connection.Insert(obj);
return result;
}
}我得到一个"Unable to cast object of type 'System.Guid' to type 'System.IConvertible'."响应。
下面是堆栈跟踪:
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发布于 2019-06-19 11:41:54
泛型Insert方法是为int主键设计的。您可以将该类型作为第一个参数传入。下面是一个示例:
connection.Insert<Guid, T>;请参阅此处的单元测试: hhttps://github.com/ericdc1/Dapper.SimpleCRUD/blob/master/Dapper.SimpleCRUDTests/Tests.cs#L682
https://stackoverflow.com/questions/56439527
复制相似问题