2017-08-06 64 views
2

考慮到CRM動力學的事實LINQ查詢被翻譯成查詢表達式(source):有沒有辦法在CRM Dynamics中查看LINQ生成的查詢表達式?

[...]的OrganizationServiceContext類包含從Microsoft Visual C#轉換LINQ查詢的基本LINQ 查詢提供 或Microsoft Visual Basic .NET語法插入到 Microsoft Dynamics CRM使用的查詢API中。 [...]

有沒有辦法看到生成的查詢表達式(因爲它可能在Linq-to-Sql或Linq-to-Entities中看到生成的SQL查詢)?

回答

6

您可以使用反射來獲取查詢對象,然後將其轉換爲FetchXML查詢以獲取可打印的查詢。這將適用於早期和遲到的查詢。

來源:https://pogo69.wordpress.com/2012/04/05/crm-linq-provider-converting-expressions-to-queryexpression-andor-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更有價值。

相關問題