-1

我正在为数据库表上的基本 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
4

1 回答 1

0

通用的 Insert 方法是为 int 主键设计的。您可以将类型作为第一个参数传入。这是一个例子:

 connection.Insert<Guid, T>;

请参阅此处的单元测试:hhttps://github.com/ericdc1/Dapper.SimpleCRUD/blob/master/Dapper.SimpleCRUDTests/Tests.cs#L682

于 2019-06-19T03:41:54.307 回答