Archive
“Sequence contains no elements” LINQ error – FIX
I was getting below error while querying “AccountSet” using LINQ in my plug-in
System.InvalidOperationException: Sequence contains no elements
Reason:-
- Exception raised when there were no records that matches to the criteria specified in my LINQ query
- I had my query statement as below
var account = orgContext.accountSet.Where(acct => (acct.name == “Rajeev”)).First();
- There were no ‘Accounts’ with name=Rajeev and using of First() resulted “Sequence contains no elements” exception
Fix:-
- Replace the method First() with FirstOrDefault().
- The method FirstOrDefault() returns a null value, if there are no records that matches to the filtering criteria
- Now my LINQ expression looks as below
var account = orgContext.accountSet.Where(acct => (acct.name == “Rajeev”)). FirstOrDefault();
🙂
Fetching user security roles using Linq in CRM 2011 Plug-in’s
Hi,
Below is the sample code to fetch the User’s security roles based on the “User Id” in the Plug-in’s using Linq
/// <summary>
/// Returns the list of User security role names
/// </summary>
private List<string> GetUserRoles(IOrganizationService service, Guid userId) {
// Create Query Expression to fetch Role Entity
var query = new QueryExpression
{
// Setting the link entity condition and filter condition criteria/
LinkEntities =
{
new LinkEntity
{
LinkFromEntityName = “role”,
LinkFromAttributeName = “roleid”,
LinkToEntityName = “systemuserroles”,
LinkToAttributeName = “roleid”,
LinkCriteria = new FilterExpression
{
FilterOperator =
LogicalOperator.And,
Conditions =
{
new ConditionExpression
{
AttributeName = “systemuserid”,
Operator = ConditionOperator.Equal,
Values =
{
userId
}
}
}
}
}
},
ColumnSet = new ColumnSet(true),
EntityName = “role”
};
// Obtain results from the query expression.
var userRoles = service.RetrieveMultiple(query);
// Get the usre role names collection
var roleNames = new List<string>();
if (userRoles != null) {
roleNames.AddRange(
from entrole in userRoles.Entities
select entrole as Role
into role
where role != null && role.RoleId != null
select role.Name);
}
return roleNames;
}
How do I call this method :-
- In your plug-in, pass the service and User Id as parameters to this method
public void Execute(IServiceProvider serviceProvider) {
context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
var service = serviceFactory.CreateOrganizationService(context.UserId);
// Get the current users Security Roles Name’s
Var roleNames = GetUserRoles(service, this.context.UserId);
}
Hope it helps 🙂