考虑到CRM Dynamics中的LINQ查询被翻译成查询表达式(source):
[...] OrganizationServiceContext类包含一个基础LINQ 从Microsoft Visual C#翻译LINQ查询的查询提供程序 或Microsoft Visual Basic .NET语法进入查询API使用 Microsoft Dynamics CRM。 [...]
有没有办法查看生成的查询表达式(因为可以在Linq-to-Sql或Linq-to-Entities中查看生成的SQL查询)?
答案 0 :(得分:7)
您可以使用反射来获取查询对象,然后将其转换为FetchXML查询以获取可打印查询。这将适用于早期绑定和后期绑定查询。
var connectionString = @"SET YOUR CONNECTION STRING";
var service = new CrmServiceClient(connectionString);
using (var xrm = service.OrganizationServiceProxy)
{
OrganizationServiceContext orgContext =
new OrganizationServiceContext(xrm);
var query = from c in orgContext.CreateQuery("contact")
join a in orgContext.CreateQuery("account")
on c["contactid"] equals a["primarycontactid"]
where (String)c["lastname"] == "Wilcox" ||
(String)c["lastname"] == "Andrews"
where ((String)a["address1_telephone1"]).Contains("(206)")
|| ((String)a["address1_telephone1"]).Contains("(425)")
select new
{
Contact = new
{
FirstName = c["firstname"],
LastName = c["lastname"]
},
Account = new
{
Address1_Telephone1 = a["address1_telephone1"]
}
};
IQueryProvider queryProvider = query.Provider;
MethodInfo translateMethodInfo = queryProvider.GetType().GetMethod("Translate");
QueryExpression queryEx = (QueryExpression)translateMethodInfo.Invoke(queryProvider, new object[] { query.Expression });
QueryExpressionToFetchXmlRequest reqConvertToFetchXml = new QueryExpressionToFetchXmlRequest { Query = queryEx };
QueryExpressionToFetchXmlResponse respConvertToFetchXml = (QueryExpressionToFetchXmlResponse)xrm.Execute(reqConvertToFetchXml);
Console.WriteLine("To FetchXML:" + Environment.NewLine + Environment.NewLine);
Console.WriteLine(respConvertToFetchXml.FetchXml);
或者,您可以使用Fiddler捕获SOAP消息中发送的实际查询文本。我以前做过这个,并没有发现它比FetchXml更有价值。