My question is quite related to this post but i am unable to assemble all the pieces together. I am trying to fetch SystemUser
using ServiceContext object, XrmServiceContext
via Linq in Plugin code as shown below:
var serviceFactory = serviceProvider.GetOrganizationServiceFactory();
var service = serviceFactory.CreateOrganizationService(context.UserId);
using (var xrmServiceContext = new XrmServiceContext(service))
{
var user = xrmServiceContext.SystemUserSet
.Where(x => x.SystemUserId.Value == context.UserId)
.First();
}
But i am getting the following InvalidCastException
:
Unable to cast object of type 'Microsoft.Xrm.Sdk.Entity' to type 'Xrm.SystemUser'.
Whereas the Early-bound classes generated through CrmSvcUtil
placed in separate assembly (other than plugin assembly).
This is quite strange as if i place the generated Early-bound classes inside the plugin assembly it works just fine.
My little research led me to create separate OrganizationServiceProxy
object but why should i create one when i am already creating IOrganizationService
using serviceFactory.CreateOrganizationService(context.UserId)
So how to solve this issue by keeping generated code outside plugin assembly?
The behavior is not strange at all. If you put the Early-Bound classes in another assembly is quite normal that your plugin can't find it, specially if the assembly is not inside the server GAC (for example).
This because when you register a plugin, you register only the plugin dll, not all the referenced assemblies.
If you want to keep the generate code outside the plugin assembly you have two options:
ILMerge link:
http://www.microsoft.com/en-us/download/details.aspx?id=17630