首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Dapper SimpleCRUD强制转换:“无法将'System.Guid‘类型的对象强制转换为’System.IConverable‘类型。”

Dapper SimpleCRUD强制转换:“无法将'System.Guid‘类型的对象强制转换为’System.IConverable‘类型。”
EN

Stack Overflow用户
提问于 2019-06-04 15:49:19
回答 1查看 1.2K关注 0票数 0

我正在为数据库表上的基本CRUD操作构建一个API。我在一个ASP.NET Web API项目中使用C#,我的服务类位于一个单独的类库中。用于对象关系管理操作的Dapper和Dapper.SimpleCRUD。

当我使用DEFAULT NEWID()将guid硬编码到数据库中时,我的create方法工作得很好。但作为最佳实践,我想在控制器类中创建一个新的guid,然后将其发送到DB。当我这样做的时候,它失败了。

在控制器中:

代码语言:javascript
复制
var newParty = new Party()
{
    Id = Guid.NewGuid(), //this is when I started getting the cast error
    Name = party.Name,
    CreatedDate = DateTime.Now
};

在存储库中:

代码语言:javascript
复制
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'."响应。

下面是堆栈跟踪:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2019-06-19 11:41:54

泛型Insert方法是为int主键设计的。您可以将该类型作为第一个参数传入。下面是一个示例:

代码语言:javascript
复制
 connection.Insert<Guid, T>;

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56439527

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档