Wazz Wazz - 27 days ago 14
C# Question

Entity Framework: Unable to create a constant value of type **. Only primitive types or enumeration types are supported in this context

I have this query:

public override IEnumerable<Order> ExecuteQuery(MovieRentalContext database)
{

return from order in database.Orders
where (customer == null || customer.Id == order.CustomerId)
select order;
}


where customer is field in the class.
There is Order class

public class Order: Entity
{
[Required]
public Copy Copy { get; set; }

public Customer Customer { get; set; }
public DateTime OrderDate { get; set; }
public DateTime EstimatedReturnDate { get; set; }
public Salesman Salesman { get; set; }

public DateTime? ActualReturnDate { get; set; }
public decimal Price { get; set; }

[ForeignKey("Customer")]
public long CustomerId { get; set; }
}


Entity contains Id. I want to get orders of a customer, but during execution the query a exception is thrown:


Unable to create a constant value of type >'MovieRental.DataAccess.Models.Customer'. Only primitive types or enumeration >types are supported in this context.


I tried everything I found but it stil doesn't work. What is the problem?

Answer

I'd say your customer == null code is causing this. EF is trying to convert this to SQL but customer is not in that context. Try and take that condition outside of the query.

ie

public override IEnumerable<Order> ExecuteQuery(MovieRentalContext database)
{
    if (customer != null)
    {
        return from order in database.Orders
            where order.CustomerId == customer.Id
            select order;
    }
    else
    {
        return from order in database.Orders
            select order;
    }

}
Comments