Atomically increment a field using SubSonic 3 ActiveRecord

落爺英雄遲暮 提交于 2019-12-23 03:18:21

问题


I'm tring to increment a field in a MySQL database using SubSonic 3 ActiveRecord. In SQL, this is what I'm after:

UPDATE people SET messages_received=messages_received+1 WHERE people_id=@id_to;

I tried the following, but it didn't seem to work (messages_received always seemed to be 1):

_db.Update<person>()
    .Set("messages_received").EqualTo(x => x.messages_received == x.messages_received + 1)
    .Where(x => x.people_id == idTo)
    .Execute();

This did work:

string sql="UPDATE people SET messages_received=messages_received+1 WHERE people_id=@id_to";
var q=new SubSonic.Query.QueryCommand(sql, _db.Provider);
q.AddParameter("id_to", idTo);
q.Provider.ExecuteQuery(q);

So I have a solution, but I'm just wondering if it's possible to do this without resorting to plain SQL?

Answer. For reference, based on Rob's suggestion below::

_db.Update<person>()
    .SetExpression("messages_received").EqualTo("messages_received+1")
    .Where<person>(x=>x.people_id==idTo)
    .Execute();

回答1:


You can use the old query tool for this and use "SetExpression":

db.Update("MyTable")
   .SetExpression("messages_received +1")
   .Where("people_id")
   .IsEqualTo(1)
   .Execute();

That's freehanded - but hopefully you get the idea :)



来源:https://stackoverflow.com/questions/2429381/atomically-increment-a-field-using-subsonic-3-activerecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!