我正在为数据库表上的基本 CRUD 操作构建一个 API。我在 ASP.NET Web API 项目中使用 C#,并且我的服务类位于单独的类库中。Dapper 和 Dapper.SimpleCRUD 用于 ORM 操作。
当我使用 将 guid 硬编码到数据库中DEFAULT NEWID()
时,我的创建方法工作正常。但为了获得最佳实践,我想在控制器类中创建一个新的 guid,然后将其发送到数据库。当我这样做时,它失败了。
在控制器中:
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