2014-07-09 32 views
0

當我創建我的表一個新的記錄,我想生成只是我的新紀錄,somethink像的主ID的JSON響應:{「PrimaryID」:123}ServiceStack如何僅使用主鍵生成Json響應?

實際上我用這個手工製作的功能:

// Inserts a new row into the PatientSession table 
    public string AddPatientSession(PatientSession p) 
    { 
     int id = (int)_dbConnection.Insert<PatientSession>(p, selectIdentity: true); 
     string Idconvert = id.ToString(); 
     string IdInsert = "{\"PatientSessionId\":" + Idconvert + "}"; 
     return IdInsert; 
    } 

但我認爲這不是最好的辦法,請給我一個建議嗎? 在此先感謝

+0

你可以看一下這個答案http://stackoverflow.com/a/1056127/2392330 – idlerboris

回答

0

非常感謝你@mythz它工作得很好我只是使用轉換函數int,因爲「Db.Insert」返回一個長類型。

// Add PatientSession via POST 
public class PatientSessionADD : IReturn<PatientSessionResponseId> 
{ 
    public int PatientSessionId { get; set; } 
    public int ByPatientId { get; set; } 
    public DateTime PatientStartSessionTime { get; set; } 
    public int PatientStartSessionByUserId { get; set; } 
    public DateTime PatientEndSessionTime { get; set; } 
    public int PatientEndSessionByUserId { get; set; } 

} 

public class PatientSessionResponseId 
{ 
    public int PatientSessionId { get; set; } 
} 


public object Post(PatientSessionADD request) 
    { 
     var p =new PatientSession() 
     { 
       ByPatientId = request.ByPatientId, 
       PatientStartSessionTime = request.PatientStartSessionTime, 
       PatientStartSessionByUserId = request.PatientStartSessionByUserId 
     }; 

     return new PatientSessionResponseId 
     { 
      PatientSessionID = Convert.ToInt16(Db.Insert<PatientSession>(p, selectIdentity: true)) 
     }; 
    } 

要恢復這個功能得到了HTTP POST消息,將其存儲在數據庫中,並返回只生成主ID的JSON響應。

有情趣,再次感謝mythz

+1

注:在.NET整數類型之間的轉換的正常方式是使用明確的轉換,例如'(INT)db.Insert(...)'。如果你打算使用'Convert',使用'Convert.ToInt32()'映射到32位整數類型,而不是'short'這個16位整數類型。 – mythz

1

如果你只是想返回一個小JSON有效載荷只有一個編號,您可以使用一個類型,只有你想返回的字段,如:

public class AddPatientSession : IReturn<PatientId> { ... } 

public class PatientId { 
    public int PatientSessionId { get; set; } 
} 

然後在服務中使用像:

public class MyServices : Service 
{ 
    public object Any(AddPatientSession request) 
    { 
     var model = request.ConvertTo<PatientSession>(); 
     return new PatientId { 
      PatientSessionId = Db.Insert(model, selectIdentity: true); 
     } 
    } 
} 

返回的對象利用ServiceStack的built-in Content Negotiation的返回在優選的Content-Type,例如序列化的對象JSON用於JSON/ajax客戶端。

您也可以返回只包含標識匿名類型:

public object Any(AddPatientSession request) 
{ 
    var model = request.ConvertTo<PatientSession>(); 
    return new { 
     PatientSessionId = Db.Insert(model, selectIdentity: true); 
    } 
} 

請求時,這也將序列化到JSON,但缺乏對類型並防止這種被稱爲與ServiceStack's generic typed Service Clients