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

标签 c# .net servicestack ormlite-servicestack

我可以将下面三个非常相似的函数合并为一个函数吗?

所有三个函数都会更新数据库中的特定列。 update语句中的匿名对象用于更新相应的列。匿名对象中的成员名称不应更改,因为它是数据库中列的名称。

我正在使用 ormlite-servicestack 进行数据库连接。我使用的数据库是 Microsoft SQLServer 2012。

函数1:

//Updating the call status.
private void UpdateCallStatus(string claimId, bool isDisconnected)
{
    _LogFactory.LogInfo(this.GetType(), "Updating call status....\n");

    IDbConnectionFactory maConnectionFactory = new DatabaseConnection().getConnection();
    using (var db = maConnectionFactory.Open())
    {
        db.Update<IVRSCallDetails>(new { IsDisconnected = isDisconnected }, where: callDetail => callDetail.ClaimId == claimId);
    }
}

函数2:

//Updating the selected dtmf by the client using the claimid.
private void UpdateDtmf(string claimId, string selectedDtmf)
{
    _LogFactory.LogInfo(this.GetType(), "Updating Selected DTMF:" + selectedDtmf + "\n");

    IDbConnectionFactory maConnectionFactory = new DatabaseConnection().getConnection();
    using (var db = maConnectionFactory.Open())
    {
        db.Update<IVRSCallDetails>(new { SelectedDTMF = selectedDtmf }, where: callDetail => callDetail.ClaimId == claimId);
    }
}

功能3:

//Updating the isCallMade value..
private void updateIsCallMade(string claimId, bool isCallMade)
{
    _LogFactory.LogInfo(this.GetType(), "Call has been made to the client with claim id: " + claimId + "\n");

    IDbConnectionFactory maConnectionFactoruy = new DatabaseConnection().getConnection();
    using (var db = maConnectionFactoruy.Open())
    {
        db.Update<IVRSCallDetails>(new { IsCallMade = isCallMade }, where: callDetail => callDetail.ClaimId == claimId);
    }
}

最佳答案

您可以将其更改为通用方法(以便能够传递类型)以及 Func<object>代替第二个参数来生成匿名对象。

private void updateData<T>(string claimId, Func<object> data)
{
    _LogFactory.LogInfo(this.GetType(), "Call has been made to the client with claim id: " + claimId + "\n");

    IDbConnectionFactory maConnectionFactoruy = new DatabaseConnection().getConnection();
    using (var db = maConnectionFactoruy.Open())
    {
        db.Update<T>(data(), where: callDetail => callDetail.ClaimId == claimId);
    }
}

使用

updateData<IVRSCallDetails>("123", () => new { IsCallMade = true});
updateData<IVRSCallDetails>("123", () => new { SelectedDTMF = selectedDtmf});

关于c# - 我可以将这三个相似的函数合并为一个函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41482666/

相关文章:

.net - 在 .NET 中,Array 只扩展了 IEnumerable,那么当 foreach 循环经过值类型数组时,是否会有装箱和拆箱?

.net - 如何在经典 ASP 中散列 UTF-8 字符串

c# - 如何以正确的编码从 HttpRequest 表单数据中读取字符串

servicestack - RouteAttribute, AttributeUsage, Inherited = true

c# - Windows Phone 8.1 中的 ItemsWrapGrid 顺序

c# - 我可以在 C# 5 和 .Net 4.5 中做哪些我在 C# 4 和 .Net 4 中不能做的事情?

c# - 使用 C# 从图形数据中删除插值点

c# - MVC - 没有带有类型 'IEnumerable<SelectListItem>' 键的 Viewdata 项目

c# - 在状态机中保存数据

c# - 客户端和服务器中的 ServiceStack 服务 URL