当我在表格中创建新记录时,我想生成一个只包含新记录主ID的json响应,有些想法:{“PrimaryID”:123}
我实际上使用这个手工制作的功能:
// 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 :(得分:1)
如果您只想返回一个只带有Id的小型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 for JSON / ajax客户端。
您还可以返回仅包含Id的匿名类型:
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调用它。
答案 1 :(得分:0)
非常感谢@mythz它运行良好我只使用转换函数来处理int因为“Db.Insert”返回一个long类型。
// 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