Is it possible to use CRM 2011 View (savedquery) with linq? I mean can I do something like this:
IEnumerable<Opportunity> GetOpportunites(CrmOrganizationServiceContext context, string viewName, Guid customerId)
{
var view = context.CreateQuery<SavedQuery>().FirstOrDefault(q => q.Name == viewName);
if(view!=null)
return from Opportunity op in view
where op.CustomerId.Id == customerId
select op;
return new List<Opportunity>();
}
It certainly would not. As Servy suggested, try it out and you’d see why.
SavedQueryhas two properties that define a view –FetchXml(the underlying query) andLayoutXml(the columns returned in the UI). In other words, it does not return the data that the view returns in the UI, but rather the definition of how the data is returned in the UI.The most cut-and-dry way to enumerate through the records you’re expecting to have returned from a view is to use a
FetchRequestdirectly. You’d have to insert your condition dynamically as an XML node in theFetchXml.You can also parse the XML filter set, then translate appropriate to Linq, but this would obviously be more challenging, perhaps unnecessarily so.
A third approach is to create a static view in the system where as a condition you set the customer equal to some arbitrary customer, and then change the customer id dynamically in the XML string.