Any() method is not working when we connect to MySql - linq

Calling Any() method on a table to check for existence of records throws an exception when we connect to MySql but it is working fine when we connect to SqlServer
I am using the following code:
public IActionResult GetCustomers()
{
DbContext db = new DbContext();
if(db.Customers.Any())//here throws an exception when connect to mysql db
{
//my code
}
return view();
}
My Exception was:
Exception has occurred: CLR/System.InvalidOperationException
An exception of type 'System.InvalidOperationException' occurred in Microsoft.EntityFrameworkCore.dll but was not handled in user code: 'No coercion operator is defined between types 'System.Int16' and 'System.Boolean'.'
at System.Linq.Expressions.Expression.GetUserDefinedCoercionOrThrow(ExpressionType coercionType, Expression expression, Type convertToType)
at System.Linq.Expressions.Expression.Convert(Expression expression, Type type, MethodInfo method)
at System.Linq.Expressions.Expression.Convert(Expression expression, Type type)
at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.CreateGetValueExpression(Expression dataReaderExpression, Int32 index, TypeMaterializationInfo materializationInfo, Boolean detailedErrorsEnabled, Boolean box)
at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.<>c__DisplayClass13_0.<CreateArrayInitializer>b__0(TypeMaterializationInfo mi, Int32 i)
at System.Linq.Enumerable.<SelectIterator>d__154`2.MoveNext()
at System.Collections.Generic.LargeArrayBuilder`1.AddRange(IEnumerable`1 items)
at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at System.Dynamic.Utils.CollectionExtensions.ToReadOnly[T](IEnumerable`1 enumerable)
at System.Linq.Expressions.Expression.NewArrayInit(Type type, IEnumerable`1 initializers)
at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.CreateArrayInitializer(CacheKey cacheKey, Boolean detailedErrorsEnabled)
at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.<Create>b__11_0(CacheKey k)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.Create(IReadOnlyList`1 types)
at Microsoft.EntityFrameworkCore.Query.Sql.DefaultQuerySqlGenerator.CreateValueBufferFactory(IRelationalValueBufferFactoryFactory relationalValueBufferFactoryFactory, DbDataReader dataReader)
at Microsoft.EntityFrameworkCore.Query.Internal.ShaperCommandContext.<NotifyReaderCreated>b__14_0(FactoryAndReader s)
at Microsoft.EntityFrameworkCore.Internal.NonCapturingLazyInitializer.EnsureInitialized[TParam,TValue](TValue& target, TParam param, Func`2 valueFactory)
at Microsoft.EntityFrameworkCore.Query.Internal.ShaperCommandContext.NotifyReaderCreated(DbDataReader dataReader)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider.GetResult[TResult](IEnumerable`1 valueBuffers, Boolean throwOnNullResult)
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ResultEnumerable`1.GetEnumerator()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
at System.Linq.Enumerable.TryGetFirst[TSource](IEnumerable`1 source, Boolean& found)
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass15_1`1.<CompileQueryCore>b__0(QueryContext qc)
at System.Linq.Queryable.Any[TSource](IQueryable`1 source, Expression`1 predicate)
at SampleEfCoreLatest.Controllers.HomeController.GetCustomers() in D:\SampleEfCoreLatest\Controllers\HomeController.cs:line 49
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()

Related

I got this error "Support user does not have permission on this operation" when I want to give GrantAccess to a record in CRM SDK 2015

I got this exception:
"Support user does not have permission on this operation"
when I try to give access to a record for a user. this is my code:
public void GrantAccess(Guid targetId, Guid principleId)
{
using (var service = new OrganizationService(_con))
{
var request = new GrantAccessRequest()
{
Target = new EntityReference(Account.EntityLogicalName, targetId),
PrincipalAccess = new PrincipalAccess()
{
AccessMask = AccessRights.ReadAccess,
Principal = new EntityReference(principleId.ToString())
}
};
service.Execute(request);
}
}
and my Constr is like:
private static readonly string ConStr = "Url=http://crm.[ourdomain].com:90/Test; Domain=[ourdomain]; Username=[user]; Password=[password];";
I cand read the data, for example I get this method:
RetrieveSharedPrincipalsAndAccessResponse
even more I "RevokeAccess" by RevokeAccessRequest, but I couldn't Grant access or modify it.
Edit1
Full Stack Error:
System.ServiceModel.FaultException`1 was unhandled
Action=http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/ExecuteOrganizationServiceFaultFault
HResult=-2146233087
Message=Support user does not have permission on this operation
Source=mscorlib
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Microsoft.Xrm.Sdk.IOrganizationService.Execute(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.ExecuteCore(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.Execute(OrganizationRequest request)
at Microsoft.Xrm.Client.Services.OrganizationService.<>c__DisplayClass19.<Execute>b__18(IOrganizationService s)
at Microsoft.Xrm.Client.Services.OrganizationService.InnerOrganizationService.UsingService[TResult](Func`2 action)
at Microsoft.Xrm.Client.Services.OrganizationService.Execute(OrganizationRequest request)
at CRMConsole.Queries.GrantAccess(Guid targetId, Guid principleId) in D:\Projects\CRM\CRMPrivileges\CRMConsole\Queries.cs:line 142
at CRMConsole.Program.Main(String[] args) in D:\Projects\CRM\CRMPrivileges\CRMConsole\Program.cs:line 20
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
I checked the user access to the Account entity, and he has the read access to it with User depth. Beside that I can share this entity in crm web page UI with current user that is in connection credential.
It's so ridiculous but the problem was in this line of code:
Principal = new EntityReference(principleId.ToString())
we must declare entity name just like this:
Principal = new EntityReference(SystemUser.EntityLogicalName,principleId)

Dynamics CRM 2013 throws SQL Timeout adding a user to a team

I have a simple but tough problem.
I am trying to add an user to a team through user interface, however I'm getting SQL Time Out for some users.
I got no plugins firing on association request. I also did not find any familiarity between the ones I am getting this error.
I have even turned the trace log on which did not give me much more details.
Following the error log generated by tracing tool.
Web Service Plug-in failed in SdkMessageProcessingStepId: {D3DE2F15-53FA-4A12-A286-346CC4BFD310}; EntityName: none; Stage: 30; MessageName: Associate; AssemblyName: Microsoft.Crm.Extensibility.InternalOperationPlugin, Microsoft.Crm.ObjectModel, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35; ClassName: Microsoft.Crm.Extensibility.InternalOperationPlugin; Exception: Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Web.Services.Protocols.LogicalMethodInfo.Invoke(Object target, Object[] values)
at Microsoft.Crm.Extensibility.InternalOperationPlugin.Execute(IServiceProvider serviceProvider)
at Microsoft.Crm.Extensibility.V5PluginProxyStep.ExecuteInternal(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
Inner Exception: Microsoft.Crm.CrmException: SQL timeout expired.
at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.Pipeline.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.MessageProcessor.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.InternalMessageDispatcher.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.ManyToManyForwardEntityAssociationCommand.AssociateEntities(EntityReference entity1, EntityReference entity2, String relationshipName, Boolean associate, ExecutionContext context)
at Microsoft.Crm.Extensibility.ManyToManyForwardEntityAssociationCommand.Execute(RelationshipProcessor processor, EntityMetadata entityMetadata, Guid entityId, EntityReferenceCollection relatedEntities, Boolean associate, ExecutionContext context)
at Microsoft.Crm.Extensibility.RelationshipProcessor.ProcessAssociation(EntityMetadata entityMetadata, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities, Boolean associate, ExecutionContext context)
at Microsoft.Crm.Extensibility.RelationshipProcessor.Associate(EntityReference entityReference, Relationship relationship, EntityReferenceCollection relatedEntities, ExecutionContext context)
Inner Exception: Microsoft.Crm.CrmException: SQL timeout expired.
Inner Exception: System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.Crm.ObjectModel.BusinessManagementUtility.LockSystemUserEntriesForTeamMembershipChange(Guid userId, ExecutionContext context)
at Microsoft.Crm.ObjectModel.TeamMembershipServiceInternal`1.Associate(BusinessEntityMoniker entityOneMoniker, BusinessEntityMoniker entityTwoMoniker, String associationRelationshipName, ExecutionContext context)
at Microsoft.Crm.BusinessEntities.BusinessProcessObject.HandleAssociationOperation(BusinessEntityMoniker entityOneMoniker, BusinessEntityMoniker entityTwoMoniker, String associationRelationshipName, Boolean createAssociation, ExecutionContext context)
at Microsoft.Crm.BusinessEntities.BusinessProcessObject.AssociateEntities(BusinessEntityMoniker entityOneMoniker, BusinessEntityMoniker entityTwoMoniker, String associationRelationshipName, ExecutionContext context)
Inner Exception: System.ComponentModel.Win32Exception: The wait operation timed out

Linq To SQL Any Throws InvalidOperationException: Sequence contains no elements

About once a day or two now my web site starts throwing and error when people try to login and no one can log in until I restart IIS. How can Any() do this and what can I do to fix it?
Here's the function throwing the exception:
public override bool ValidateUser(string username, string password)
{
var db = Access.Context;
var query =
from p in db.Players
where p.PlayerName == username
&& p.Password == password
select p
;
return query.Any();
}
Other LINQ to SQL queries work fine. Here's the stack trace.
InvalidOperationException: Sequence contains no elements
System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) +1151
System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) +113
System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +344
System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute(Expression expression) +23
System.Linq.Queryable.Any(IQueryable`1 source) +243
FortyTwoAccess.PlayerProvider.ValidateUser(String username, String password) in C:\dev\FortyTwo\FortyTwoAccess\PlayerProvider.cs:114
FortyTwoClient.Models.AccountMembershipService.ValidateUser(String userName, String password) in C:\dev\FortyTwo\FortyTwoClient\Models\AccountModels.cs:117
FortyTwoClient.Controllers.AccountController.LogOn(LogOnModel model, String returnUrl) in C:\dev\FortyTwo\FortyTwoClient\Controllers\AccountController.cs:42
lambda_method(Closure , ControllerBase , Object[] ) +157
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
Does works this?
public override bool ValidateUser(string username, string password)
{
var db = Access.Context;
return db.Players.Any(p => p.PlayerName == username && p.Password == password);
}
The fix for this was to not use a class variable to save the context and instead instantiate the context locally in each method wrapped in a using.

Microsoft Dynamics 2011 N:N LINQ query with where clause containing Guid

I have constructed a simple query to return a Users Team membership (N: N relationship). This works fine for all users, however, when I add a where clause to restrict to a specific user it throws a fault exception (see stack trace below).
Strangely this works fine with "where Users.FullName.StartsWith("Alex")". Does the Dynamics CRM SDK LINQ implementation not support Guides in where clauses?
Any advice?
Example code
using (var service = new OrganizationService("Xrm"))
{
using (var xrm = new XrmServiceContext(service))
{
var AlexUser = xrm.SystemUserSet.Where(p => p.FullName.StartsWith("Alex")).First();
var AlexID = AlexUser.Id;
var Test =
from Users in xrm.SystemUserSet
join TeamMemberships in xrm.TeamMembershipSet on Users.Id equals TeamMemberships.SystemUserId
join Teams in xrm.TeamSet on TeamMemberships.TeamId equals Teams.Id
where Users.Id == AlexID // <-- problematic where clause
orderby Users.FullName
select new
{
FullName = Users.FullName,
UserID = Users.Id,
TeamName = Teams.Name
};
var Test1 = Test.ToList();
}
}
Stacktrace:
Server stack trace: at
System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime
operation, ProxyRpc& rpc) at
System.ServiceModel.Channels.ServiceChannel.Call(String action,
Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
Object[] outs, TimeSpan timeout) at
System.ServiceModel.Channels.ServiceChannel.Call(String action,
Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
Object[] outs) at
System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
methodCall, ProxyOperationRuntime operation) at
System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
message)
Exception rethrown at [0]: at
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
reqMsg, IMessage retMsg) at
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
msgData, Int32 type) at
Microsoft.Xrm.Sdk.IOrganizationService.Execute(OrganizationRequest
request) at
Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.ExecuteCore(OrganizationRequest
request) at
Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.Execute(OrganizationRequest
request) at
Microsoft.Xrm.Client.Services.OrganizationService.<>c__DisplayClass19.b__18(IOrganizationService
s) at
Microsoft.Xrm.Client.Services.OrganizationService.InnerOrganizationService.UsingService[TResult](Func2 action) at Microsoft.Xrm.Client.Services.OrganizationService.Execute(OrganizationRequest request) at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.Execute(OrganizationRequest request) at Microsoft.Xrm.Sdk.Linq.QueryProvider.RetrieveEntityCollection(OrganizationRequest request, NavigationSource source) at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute(QueryExpression qe, Boolean throwIfSequenceIsEmpty, Boolean throwIfSequenceNotSingle, Projection projection, NavigationSource source, List1 linkLookups,
String& pagingCookie, Boolean& moreRecords) at
Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute[TElement](QueryExpression
qe, Boolean throwIfSequenceIsEmpty, Boolean throwIfSequenceNotSingle,
Projection projection, NavigationSource source, List1 linkLookups) at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute[TElement](Expression expression) at Microsoft.Xrm.Sdk.Linq.QueryProvider.GetEnumerator[TElement](Expression expression) at Microsoft.Xrm.Sdk.Linq.Query1.GetEnumerator() at
System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at
aspirets.crm.test.Program.Main(String[] args) in
C:\Users\a_marshall\documents\visual studio
2010\Projects\aspirets.crm\aspirets.crm.test\Program.cs:line 37 at
System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[]
args) at System.AppDomain.ExecuteAssembly(String assemblyFile,
Evidence assemblySecurity, String[] args) at
Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
ignoreSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Threading.ThreadHelper.ThreadStart()
Instead of Users.Id, try Users.SystemUserId. Similarly, instead of Teams.Id, try Teams.TeamId.
As for the reason why this works, I'm not aware of any documentation that states this, but because entities in the generated early-binding file inherit from Entity, they necessarily have an Id property. However, because the early-bound OrganizationServiceContext maps entity attributes directly to the CRM database, the tables of which don't contain an Id column, using the Id attribute with the LINQ provider won't work, so you'd have to use the actual database/schema names.

Linq to CRM (early bound) join statement throws exception when lambda expression doesn't

Is there a bug in the Microsoft linq to CRM provider, or am I doing something that linqToCrm doesn't support?
I have a simple function that determines if the user is assigned a role which doesn't work.
public static bool IsSystemUserInRole(Guid systemUserId,
string roleName,
Microsoft.Xrm.Sdk.IOrganizationService service)
{
using (var crmService = new CrmContext(service))
{
return (from sr in crmService.SystemUserRolesSet
join r in crmService.RoleSet
on sr.RoleId.Value equals r.RoleId.Value
where sr.SystemUserId.Value == systemUserId && r.Name == roleName
select sr.SystemUserId).FirstOrDefault() != null;
}
}
But strangely enough, if I rewrite it as two lambda expressions, it works fine.
public static bool IsSystemUserInRole(Guid systemUserId,
string roleName,
Microsoft.Xrm.Sdk.IOrganizationService service)
{
using (var crmService = new CrmContext(service))
{
var role = crmService.RoleSet.FirstOrDefault(r => r.Name == roleName);
return role != null
&& crmService.SystemUserRolesSet.FirstOrDefault(
ur => ur.SystemUserId == systemUserId
&& ur.RoleId == role.RoleId) != null;
}
}
The Exception is
System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]: 'SystemUserRoles' entity doesn't contain attribute with Name = 'name'. (Fault Detail is equal to Microsoft.Xrm.Sdk.OrganizationServiceFault).
and the stack trace is
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Microsoft.Xrm.Sdk.IOrganizationService.Execute(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.ExecuteCore(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.Execute(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.Execute(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.RetrieveEntityCollection(OrganizationRequest request, NavigationSource source)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute(QueryExpression qe, Boolean throwIfSequenceIsEmpty, Boolean throwIfSequenceNotSingle, Projection projection, NavigationSource source, List1 linkLookups, String& pagingCookie, Boolean& moreRecords)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute[TElement](QueryExpression qe, Boolean throwIfSequenceIsEmpty, Boolean throwIfSequenceNotSingle, Projection projection, NavigationSource source, List1 linkLookups)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute[TElement](Expression expression)
at Microsoft.Xrm.Sdk.Linq.QueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source)
at CRM.Business.IntegrationServices.SystemUserService.IsSystemUserInRole(Guid systemUserId, String roleName, IOrganizationService service)
at CRM.Plugin.OnExecute(IServiceProvider provider)
Where statements from different entities need to be introduced in separate where statements.
The where clause applies a filter to the results, often using a
Boolean expression. The filter specifies which elements to exclude
from the source sequence. Each where clause can only contain
conditions against a single entity type. A composite condition
involving multiple entities is not valid. Instead, each entity should
be filtered in separate where clauses.
The below should probably take care of it.
public static bool IsSystemUserInRole(Guid systemUserId,
string roleName,
Microsoft.Xrm.Sdk.IOrganizationService service)
{
using (var crmService = new CrmContext(service))
{
return (from sr in crmService.SystemUserRolesSet
join r in crmService.RoleSet
on sr.RoleId.Value equals r.RoleId.Value
where sr.SystemUserId.Value == systemUserId
where r.Name == roleName
select sr.SystemUserId).FirstOrDefault() != null;
}
}

Resources