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

entity-framework entity-framework-6

Question

I'm creating anIQueryable<int> and the alias of the int column in the produced SQL may change based on the user's criterion selections. Sometimes the column name is used, and other times it's something like "C1." I'm wondering whether there's a method to get the query's created alias name, which is similar to my inquiry here where I ask How can I get an Entity Framework query's parameters?.

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

Accepted Answer

Although it doesn't directly address my initial query, I wanted to share a fantastic method I just discovered that enables me to control what the alias would be in SQL Server.

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

I can now do mass insert and update operations by fusing this little slice of SQL with my very sophisticated IQueryable. like 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 need to provide the query's parameters, which you can do by using the guidance provided in the example on my prior question. How can I get an Entity Framework query's parameters?

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