CommandText for IUpdatable/ISelectInsertable/IValueInsertable
See original GitHub issueFor each of the above, is there a way to get the command text for before they are executed & without modifying the database?
I know I can get the text of the last command from a DataConnection by using LastQuery after the command has been executed, but I need it before.
IQueryable<T>.ToString()
seems to work for select commands.
The following works using transactions with rollback calls, but this it far from ideal and obvious wouldn’t be used production code:
public static class DataConnectionExtensions {
public static string LastQueryUpdatable = string.Empty;
public static string LastQuerySelectInsertable = string.Empty;
public static string LastQueryValueInsertable = string.Empty;
public static string LastQuery<T>(this DataConnection dataConnection, IUpdatable<T> updatable) {
var sql = $"Cannot get {nameof(LastQuery)} for {updatable}";
using(var t = dataConnection.BeginTransaction()) {
updatable.Update();
sql = dataConnection.LastQuery;
t.Rollback();
}
LastQueryUpdatable = sql;
return sql;
}
public static string LastQuery<T, TTarget>(this DataConnection dataConnection, ISelectInsertable<T, TTarget> selectInsertable) {
var sql = $"Cannot get {nameof(LastQuery)} for {selectInsertable}";
using(var t = dataConnection.BeginTransaction()) {
selectInsertable.Insert();
sql = dataConnection.LastQuery;
t.Rollback();
}
LastQuerySelectInsertable = sql;
return sql;
}
public static string LastQuery<T>(this DataConnection dataConnection, IValueInsertable<T> valueInsertable) {
var sql = $"Cannot get {nameof(LastQuery)} for {valueInsertable}";
using(var t = dataConnection.BeginTransaction()) {
valueInsertable.Insert();
sql = dataConnection.LastQuery;
t.Rollback();
}
LastQueryValueInsertable = sql;
return sql;
}
}
Issue Analytics
- State:
- Created 3 years ago
- Comments:8 (5 by maintainers)
Top Results From Across the Web
SqlCommand.CommandText Property
Gets or sets the Transact-SQL statement, table name or stored procedure to execute at the data source.
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Just adding for another use case…
Sometimes I have to make SQL for certain Insert or update statements that are not executed via code (i.e. for Rollout/rollback type scripts.) Getting these strings lets me use Linq2Db in Linqpad to generate the SQL for these scripts.
Good point, maybe it is good to add additional API for script generation, for example with inlined parameters. I’m also doing such SQL generation, but usually copy SQL from debugger.