sqlite - 如何使用OrmLite的UpdateOnly方法进行部分表更新?

标签 sqlite servicestack ormlite-servicestack

我正在尝试更新表格上的两个字段。我已经尝试了几件事,但是我尝试过的更新会影响其他领域。这是我的代码:

// Updates a row in the PatientSession table. Note that this call updates
public string UpdateEndPatientSession(PatientSession p)
{       
    // Update fields I set but reset data other fields
    _dbConnection.Update<PatientSession>(p);

    // Rename all fields of the column
    _dbConnection.UpdateOnly(new PatientSession { Id = p.Id, PatientEndSessionTime = p.PatientEndSessionTime, PatientEndSessionByUserId = p.PatientEndSessionByUserId }, (PatientSession patient) => new { patient.Id, patient.PatientEndSessionTime, patient.PatientEndSessionByUserId });
    _dbConnection.Update<PatientSession>(new { PatientSessionId = 10, PatientEndSessionTime = sessiontime, PatientEndSessionByUserId = 159 });
    string IdInsert = "{\"PatientSessionId\":" + p.Id + "}";
    return IdInsert;
}


我按照ServiceStack tutorial上的说明进行操作,但无法正常工作。我也不明白如何在不选择具有主要ID的行的情况下更新行。

我尝试了基本的SQL请求,但得到了SQLiteException

string patientendsessiontime = p.PatientEndSessionTime.ToString();
string patientendsessionbyuserid = p.PatientEndSessionByUserId.ToString();
string patientsessionid = p.Id.ToString();

string SQLraw = "UPDATE PatientSession SET PatientEndSessionTime = " + patientendsessiontime + ", PatientEndSessionByUserId =  " + patientendsessionbyuserid + " WHERE PatientSessionId = " + patientsessionid + "";
_dbConnection.ExecuteSql(SQLraw);




我只想进行部分更新。

最佳答案

您需要在WHERE语句中指定UpdateOnly子句。

public string UpdateEndPatientSession(PatientSession p)
{
    _dbConnection.UpdateOnly(
        p, 
        onlyFields: ps => new { ps.PatientEndSessionTime, ps.PatientEndSessionByUserId },
        where: ps => ps.Id == p.Id
    );
    ...


句法:

_dbConnection.UpdateOnly(
    p, // The source data object
    onlyFields: ps => ... , // The fields you want from the source data object
    where: ps => ... // The record match condition
);


有关更多示例,请参见update documentation



顺便说一句,我看到您正在返回string类型,然后构建一个JSON响应:


字符串IdInsert =“ {\” PatientSessionId \“:” + p.Id +“}”


您是否知道您可以简单地将返回值设置为object然后执行:

return new { PatientSessionId = p.Id };


在我看来,您不想自己处理JSON的序列化。

关于sqlite - 如何使用OrmLite的UpdateOnly方法进行部分表更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24628924/

相关文章:

c# - Microsoft.Data.SQLite : Library e_sqlite3 not found

ios - 应用因数据存储而被拒绝

python - 我如何知道如何正确使用方法来访问某些变量/数据集?

asp.net-mvc - ServiceStack MemoryCacheClient 不缓存

c# - 无法从 OrmLiteConfigExtensions (ServiceStack.OrmLite.Core) 加载 System.ComponentModel.Annotations

mysql - SQL查询-选择不满足条件的元素

c# - 带有 ServiceStack 的 List 和 Dictionary 的 AngularJS 友好返回类型

httpwebrequest - 使用 ServiceStack.Client 超时

c# - 我可以将这三个相似的函数合并为一个函数吗?

ServiceStack.OrmLite 从一个存储过程中获取多个结果集