データコンテキストからDbCommandを使用しました。IQueryable が必要です。System.Data.Linq.DataContext.GetCommand(System.Linq.IQueryable)
概要: データ ソースに対して実行する SQL ステートメントまたはストアド プロシージャを表します。コマンドを表すデータベース固有のクラスの基本クラスを提供します。
public void GetSqlCommand()
{
const string sc2 = @"Server=SQLServerName;Database=DatabaseName;Trusted_Connection=True;";
using (var dc = new DataContext(sc2))
{
var query = dc.GetTable<Users>()
.Join(dc.GetTable<Phone>(),
x => x.UserId,
y => y.LastUserId,
(x, y) => new { User = x, Phone = y }).Select(x => x);
DbCommand command = dc.GetCommand(query);
Assert.IsNotNull(command.CommandText);
}
}
次に、このようなものを提供します
SELECT [t0].[UserId], [t0].[Login], [t0].[FullName], [t0].[LastUserId], [t0].[LastDateTime], [t1].[PhoneId], [t1].[PhoneNumber], [t1].[LastUserId] AS [LastUserId2], [t1].[LastDateTime] AS [LastDateTime2]
FROM [dbo].[Users] AS [t0]
INNER JOIN [dbo].[Phone] AS [t1] ON ([t0].[UserId]) = [t1].[LastUserId]
クエリから SQL を構築するためにフレームワークで使用されるコードが必要なようです。これは、SQLProvider の MSFT 参照コードへのリンクです。そこに答えがあると思います。
SQLプロバイダー
このメソッドを見てください。渡したクエリ式のクエリ情報が返されます。Query Info には、上で述べた結果の CommandText があります。
internal QueryInfo[] BuildQuery(Expression query, SqlNodeAnnotations annotations) {.. calls the private BuildQuery..}
private QueryInfo[] BuildQuery(ResultShape resultShape, Type resultType, SqlNode node, ReadOnlyCollection<Me.SqlParameter> parentParameters, SqlNodeAnnotations annotations) {...}
……
internal class QueryInfo {
SqlNode query;
string commandText;
ReadOnlyCollection<SqlParameterInfo> parameters;
ResultShape resultShape;
Type resultType;
internal QueryInfo(SqlNode query, string commandText, ReadOnlyCollection<SqlParameterInfo> parameters, ResultShape resultShape, Type resultType) {
this.query = query;
this.commandText = commandText;
this.parameters = parameters;
this.resultShape = resultShape;
this.resultType = resultType;
}
internal SqlNode Query {
get { return this.query; }
}
internal string CommandText {
get { return this.commandText; }
}
internal ReadOnlyCollection<SqlParameterInfo> Parameters {
get { return this.parameters; }
}
internal ResultShape ResultShape {
get { return this.resultShape; }
}
internal Type ResultType {
get { return this.resultType; }
}
}
GetCommand はBuild Queryメソッドも呼び出して SQL を生成し、最初のクエリからコマンド テキストを取得することがわかります。
DbCommand IProvider.GetCommand(Expression query)
{
this.CheckDispose();
this.CheckInitialized();
if (query == null) {
throw Error.ArgumentNull("query");
}
this.InitializeProviderMode();
SqlNodeAnnotations annotations = new SqlNodeAnnotations();
QueryInfo[] qis = this.BuildQuery(query, annotations);
QueryInfo qi = qis[qis.Length - 1];
DbCommand cmd = this.conManager.Connection.CreateCommand();
cmd.CommandText = qi.CommandText;
cmd.Transaction = this.conManager.Transaction;
cmd.CommandTimeout = this.commandTimeout;
AssignParameters(cmd, qi.Parameters, null, null);
return cmd;
}