开发者

"Simultaneous" insert if missing and log entry using Linq

开发者 https://www.devze.com 2023-04-13 06:13 出处:网络
In timing our code, I noticed that there is a substantial transaction time each time Linq communicates with SQL Server. In the past, when we used SQL directly, we could place multiple statements and s

In timing our code, I noticed that there is a substantial transaction time each time Linq communicates with SQL Server. In the past, when we used SQL directly, we could place multiple statements and send it at once. Is there a way to do this in Linq? In particular, I have two tables, a Log table and a UHAs (userhostaddress) table. If the uha is not already in the UHAs table, it must be inserted, and then the Log entry made with the uhaid. In Linq, this takes three calls, once to verify that the uha does not exist, once to insert it, and once for the log. Can I do this in one call to the database?

    var uha = db.UHAs.Where(u => u.userhostaddress == _userHostAddress).FirstOrDefault();
    if (uha == null)
    {
        var newUha = new UHA()
        {
            userhostaddress = _userHostAddress
        };
        db.UHAs.InsertOnSubmit(newUha);
        db.SubmitChanges();     // 2. Seco开发者_高级运维nd call

        uha = newUha;
    }

    SHA1 sha1 = SHA1.Create();
    var newLog= new Log()
    {                    
        requested = DateTime.UtcNow,
        uhaid = uha.uhaid,
        query = _query,
        queryhash = sha1.ComputeHash(Encoding.UTF8.GetBytes(_query))
    };
    db.Log.InsertOnSubmit(newLog);
    db.SubmitChanges();


Since you are using the same instance of the data context you only need to call SubmitChanges() once. That will execute all commands at once rather than making multiple trips to the sql server.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号