30% OFF - 10th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY10
Entity Framework Unable to create a constant value Exception
Exception: Unable to create a constant value of type [Object]. Only primitive types or enumeration types are supported in this context.
Using lambda expression, there are certain things that you can express in C#, but Entity Framework doesn't know how to convert it to SQL. For example, retrieve all the invoices of any particular customer.
using (var context = new CustomerContext()) { var invoices = context.Invoices .Where(i => i.Customer == customer) .ToList(); }
In this example, entity framework is trying to convert a whole customer object equality into a database query.
StackOverflow Related Questions
- Only primitive types or enumeration types are supported in this context
- Error: Only primitive types or enumeration types are supported in this context EF
Solution
The easiest solution to handle this exception is to query data in entity framework queries using constant values, much like SQL queries by comparing the IDs of the object and not the object itself in Where method.
using (var context = new CustomerContext()) { var invoices = context.Invoices .Where(i => i.Customer.CustomerID == customer.CustomerID) .ToList(); }
ZZZ Projects