HHHome HHHome - 1 month ago 6
C# Question

Unable to create a constant value of type

I am having issues with the following linq query:

conv.ConversationUsers = await (from cu in db.ConversationUsers
where conversationCreationDto.Users.Any(u => cu.UserId == u.UserId)
select cu).Include(u => u.Conversation).Include(u => u.User).ToListAsync();


conversationCreationDto.Users
is a local collection of User objects.
db.ConversationUsers
is a db table

The error that is returned:


"Unable to create a constant value of type 'DM.DTO.UserDTO'. Only primitive types or enumeration types are supported in this context."


I understand that I need to change the order of the comparison, I need to say 'Does cu contain any of these Ids' but I cannot do this because cu isnt a collection. is there a way for me to make cu a collection that I can do a .Any on?

Answer

Project conversationCreationDto.Users into List<int> with UserIds outside of your query and use Contains instead of Any:

var ids = conversationCreationDto.Users.Select(u => u.UserId).ToList();
conv.ConversationUsers = await (from cu in db.ConversationUsers
     where ids.Contains(cu.UserId)
     select cu).Include(u => u.Conversation).Include(u => u.User).ToListAsync();

That should result in WHERE UserId IN (...) in generated SQL.

Comments