How to implement Select For Update in EF Core
<p>As far as I've understood it, there is no option in EF (and EF Core) to explicitly lock resources which I'm querying, but I'll need this functionality quite often and don't really feel like falling back to writing select statements every time I'll need it. </p>

<p>Since I only need it for postgres and <a href="https://www.postgresql.org/docs/current/static/sql-select.html" rel="noreferrer">according to the spec</a> <code>FOR UPDATE</code> is the last item in the query, the easiest I thought about implementing it was to get the select statement as described here: <a href="https://stackoverflow.com/questions/11342669/in-linq-to-entities-can-you-convert-an-iqueryable-into-a-string-of-sql">In Linq to Entities can you convert an IQueryable into a string of SQL?</a> and append <code>FOR UPDATE</code> and directly execute it. However this will either give me a query with parameter placeholders or not a prepared query meaning that caching for execution plan won't really work on postgres, so in either way it's a no go.</p>

<p>Linq to SQL had the method <a href="https://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.getcommand(v=vs.110).aspx" rel="noreferrer"><code>DataContext.GetCommand</code></a> but there doesn't seem to be anything equivalent in EF and specially EF Core. I also had a look at EntityFramework.Extended and their batch updates / deletes but since they have to transform the select statement into a different statement they need to deal with far more complexity than me and so I hope for a simpler solution.</p>

<p><strong>Update:</strong></p>

<p>In case it wasn't clear from the description, I want to create an extension method like this:</p>

<pre><code>public static IList&lt;T&gt; ForUpdate (this IQueryable&lt;T&gt; me)
{
    // this line is obviously what is missing for me :)
    var theUnderlyingCommand = me.GetTheUnderlyingDbCommandOrSimilar();

    theUnderlyingCommand.Text += "FOR UPDATE";
    return me.ToList();
}
</code></pre>

<p>This way, other developers can use EF via Linq as with all other procedures and instead of running <code>.ToList()</code> they'd run <code>.ForUpdate()</code>. (For Update executes the query on purpose to make the implementation easier, and also because <code>FOR UPDATE</code> is the last option supported by postgres, afterwards there shouldn't be anything else anymore)</p>