How can I get the column aliases generated by Entity Framework?

entity-framework entity-framework-6

Question

I am building an IQueryable<int> and depending on what criteria the user selects, the alias of the int column in the generated SQL may vary. Sometimes it's the name of the column and sometimes it's something like "C1". Similar to my question here where I ask How can I get the parameters of an Entity Framework query?, I am wondering if there's a way to get the generated alias name of the query?

1
0
5/23/2017 11:44:16 AM

Accepted Answer

This doesn't directly answer my original question, but I just learned of an awesome trick that allows me to override what the alias would be (in SQL Server) and I had to share it.

var query = myIQueryable.ToString();
var sql = $@"SELECT x.myAlias
             FROM ({query}) x(myAlias)";

Now I can combine my super-complex IQueryable with this little snippet of SQL to do bulk insert and update operations. Such as:

var query = myIQueryable.ToString();
var sql = $@"INSERT INTO dbo.myTable (col1)
             SELECT x.myAlias
             FROM ({query}) x(myAlias)";

Or

var query = myIQueryable.ToString();
var sql = $@"UPDATE dbo.myTable
             SET Col1 = 1
             FROM dbo.myTable
             JOIN ({query}) x(myAlias) ON x.myAlias = dbo.myTable.SomeColumn";

Of course, you still have to plug in the parameters of the query, which you can get by following the example given on my previous question: How can I get the parameters of an Entity Framework query?

0
5/23/2017 11:58:47 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow