使用C#将Lambda表达式转换为SQL UPDATE语句

Ste*_*ols 4 c# lambda entity-framework

库或代码是否可用于从lambda表达式创建SQL Update语句?我们希望使用强类型的lambda表达式来进行更新,而不是事先调用对象或使用字符串.我在考虑这样的事情.

Update<Task>(
    u => u.UserID = 1, u.TaskCount += 1, //Update
    w => w.Priority != "High" && (w.Status != "Complete" || w.Status == null) //Where
);
Run Code Online (Sandbox Code Playgroud)

哪个会粗略地翻译成..

UPDATE Tasks SET UserID = 1, TaskCount = TaskCount + 1
WHERE Priority <> "High" AND (Status <> "Complete" OR Status = null)
Run Code Online (Sandbox Code Playgroud)

我应该提到我们目前正在使用Entity Framework和Postgres.

Ste*_*ols 7

我终于想出办法来做到这一点.基本上,从实体框架,LINQ-to-SQL或其他ORM获取生成的SQL,然后解析WHERE子句.这样我就不必手动解析lambda了.然后从匿名类型创建UPDATE子句.结果如下:

Update<Task>(
    new { UserID = 1, TaskCount = IncrementOf(1), SomeOtherField = DdNull } //Update
    w => w.Priority != "High" && (w.Status != "Complete" || w.Status == null) //Where
);

Delete<Task>(w => w.UserID == userID && w.Status != "Complete");
Run Code Online (Sandbox Code Playgroud)

这允许我更新/删除值而不先拉它们.

它的代码看起来像这样......

protected void Update<T>(object values, Expression<Func<T, bool>> where) where T : class
{
    Domain.ExecuteStoreCommand(
        "UPDATE {0} SET {1} WHERE {2};",
        GetTableString<T>(),
        GetUpdateClauseString(values),
        GetWhereClauseString(where)
        );
}

protected string GetUpdateClauseString(object obj)
{
    string update = "";
    var items = obj.ToDictionary();
    foreach (var item in items)
    {
        //Null
        if (item.Value is DBNull) update += string.Format("{0} = NULL", GetFieldString(item.Key));

        //Increment
        else if (item.Value is IncrementExpression) update += string.Format("{0} = {0} + {1}", GetFieldString(item.Key), ((IncrementExpression)item.Value).Value.ToString());

        //Decrement
        else if (item.Value is DecrementExpression) update += string.Format("{0} = {0} - {1}", GetFieldString(item.Key), ((DecrementExpression)item.Value).Value.ToString());

        //Set value
        else update += string.Format("{0} = {1}", GetFieldString(item.Key), GetValueString(item.Value));

        if (item.Key != items.Last().Key) update += ", ";
    }
    return update;
}

protected string GetWhereClauseString<T>(Expression<Func<T, bool>> where) where T : class
{
    //Get query
    var query = ((IQueryable<T>)Domain.CreateObjectSet<T>());
    query = query.Where(where);
    ObjectQuery queryObj = (ObjectQuery)query;

    //Parse where clause
    string queryStr = queryObj.ToTraceString();
    string whereStr = queryStr.Remove(0, queryStr.IndexOf("WHERE") + 5);

    //Replace params
    foreach (ObjectParameter param in queryObj.Parameters)
    {
        whereStr = whereStr.Replace(":" + param.Name, GetValueString(param.Value));
    }

    //Replace schema name
    return whereStr.Replace("\"Extent1\"", "\"Primary\"");
}
Run Code Online (Sandbox Code Playgroud)


Kir*_*rst 3

您可以执行类似的操作,但是可以将哪些内容转换为 SQL 以及需要将哪些内容拉回到应用程序中。

您需要做的是为您的Update方法提供一个Action(这是“更新”部分)和一个Expression(作为“where”子句)。

public void Update(Action<T> updateStatement, Expression<Func<T, bool>> where)
{
    // get your object context & objectset, cast to IQueryable<T>
    var table = (IQueryable<T>)objectContext.CreateObjectSet<T>();        

    // filter with the Expression
    var items = table.Where(where);

    // perform the Action on each item
    foreach (var item in items)
    {
        updateStatement(item);
    }

    // save changes.
}
Run Code Online (Sandbox Code Playgroud)

然后你可以用类似的方式调用你的更新

repository.Update(s => s.Name = "Me", w => w.Id == 4);
Run Code Online (Sandbox Code Playgroud)