kenzolek
kenzolek

Reputation: 344

LINQ query. Only primitive types or enumeration types are supported in this context

I want to create LINQ query checking created automatic permissions created in current month. I have list of permissions included pairs employee and company and then I want to get list of permissions created in current month for these couples. Unfortunately it return exception: "Additional information: Unable to create a constant value of type 'Exence.CRM.Dto.AutomaticPermissionDto'. Only primitive types or enumeration types are supported in this context". How can I fix the second query?

var automaticPermission = await context.AutomaticPermission
                    .AsNoTracking()
                    .Select(x => new AutomaticPermissionDto
                    {
                        EmployeeId = x.EmployeeId,
                        CompanyId = x.CompanyId
                    }).ToListAsync();

                var currentlyAutomaticPermissions = await context.Permissions
                        .Where(x => automaticPermission.Select(c => c.EmployeeId).Contains(x.EmployeeId) &&
                                    automaticPermission.Select(c => c.CompanyId).Contains(x.CompanyId) &&
                                    x.IssueDate.Month == DateTime.Today.Month)
                        .AsNoTracking()
                        .ToListAsync();

Upvotes: 1

Views: 323

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109080

It seems that you're looking for Permissions that have matching data in AutomaticPermission. You can do that more efficiently in one LINQ query, which at the same time will solve your issue:

var currentlyAutomaticPermissions = await context.Permissions
        .Where(x => context.AutomaticPermission
                           .Any(at => at.EmployeeId == x.EmployeeId 
                                   && at.CompanyId == x.CompanyId)
                 && x.IssueDate.Month == DateTime.Today.Month)
        .AsNoTracking()
        .ToListAsync();

Not only is this more efficient, I also think the match is more accurate, because it matches pairs of CompanyId and EmployeeId. The original query will find Permissions of which CompanyId and EmployeeId occur in AutomaticPermission, but not necessarily as pair.

Upvotes: 3

Related Questions