【问题标题】:Why is service stack returning a Int64 instead of Int32?为什么服务堆栈返回 Int64 而不是 Int32?
【发布时间】:2019-01-11 22:28:48
【问题描述】:

我的模型 SecPermission 有 Id = int 列,即 Int32。当我添加新记录时,为什么它会将新添加的 ID 返回为 Int64?

服务方式

public object Post(AddPermission request)
        {
            var perm = request.ConvertTo<SecPermission>();
            perm.AuditUserId = UserAuth.Id;
            LogInfo(typeof(SecPermission), request, LogAction.Insert);
            return Db.Insert(perm);
        }

单元测试代码

     using (var service = HostContext.ResolveService<SecurityService>(authenticatedRequest))
                    {
///**this line is returning an object with Int64 in it.
                        int id = (int) service.Post(new AddPermission { Name = name, Description = "TestDesc" });
                        service.Put(new UpdatePermission { Id = permission, Name = name,Description = "TestDesc" });
                        service.Delete(new DeletePermission { Id = Convert.ToInt32(id)});
                    }

     public class SecPermission : IAudit
            {
                [AutoIncrement]
                [PrimaryKey]
                public int Id { get; set; }

            [Required]
            [StringLength(50)]
            public string Name { get; set; }

            [Required]
            [StringLength(75)]
            public string Description { get; set; }

            [Required]
            public PermissionType PermissionType { get; set; }

            public int AuditUserId { get; set; }
            public DateTime AuditDate { get; set; } = DateTime.Now;
        }

【问题讨论】:

    标签: servicestack


    【解决方案1】:

    您永远不应该在 ServiceStack 服务中返回值类型,它必须是引用类型,通常是类型化响应 DTO,但也可以是原始数据类型,如 stringbyte[],但绝不应该是值类型,如整数,在某些 ServiceStack 功能中将无法工作。

    对于此服务,我将返回 SecPermission 对象或 AddPermissionResponse 对象,结果值中包含整数。

    请注意,OrmLite Insert() API 返回一个 long,这就是您看到 long 的原因,但是您需要 call Save() or specify selectIdentity:true 以获取新插入的 [AutoIncrement] 主键的 id,例如:

    var newId = db.Insert(perm, selectIdentity:true);
    

    Db.Save(perm);
    var newId = perm.Id; //auto populated with auto incremented primary key
    

    此外,您不需要在 OrmLite 中同时使用 [PrimaryKey][AutoIncrement],因为 [AutoIncrement] 自己指定主键,就像使用 Id property convention 一样。

    此外,如果您要直接调用服务,您也可以键入响应以避免强制转换,例如:

    public SecPermission Post(AddPermission request)
    {
        //...
        Db.Save(perm);
        return perm;
    }
    

    那么直接调用就不需要强制转换了,例如:

    var id = service.Post(new AddPermission { ... }).Id;
    

    ServiceStack 中使用 object 或像 SecPermission 这样的类型化响应没有行为差异,尽管最好使用 IReturn&lt;T&gt; 接口标记在您的请求 DTO 上指定它,例如:

    public AddPermission : IReturn<SecPermission> { ... }
    

    因为它在从服务客户端调用时启用端到端类型化 API,例如:

    SecPermission response = client.Post(new AddPermission { ... });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-17
      • 2011-10-19
      • 1970-01-01
      • 2015-06-21
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      相关资源
      最近更新 更多