Linq Query continues to generate errors "A constant variable of type System could not be created. Object ", Why?

.net c# entity-framework linq winforms

Question

The code example is as follows:

private void loadCustomer(int custIdToQuery) 
    {
        var dbContext = new SampleDB();
        try
        {
            var customerContext = from t in dbContext.tblCustomers      // keeps throwing:
                                   where t.CustID.Equals(custIdToQuery) // Unable to create a constant value of type 'System.Object'. 
                                   select new                           // Only primitive types ('such as Int32, String, and Guid') 
                                   {                                    // are supported in this context.
                                       branchId = t.CustomerBranchID,   //
                                       branchName = t.BranchName        //
                                   };                                   //

            if (customerContext.ToList().Count() < 1) //Already Tried customerContext.Any()
            {
                lstbCustomers.DataSource = customerContext;
                lstbCustomers.DisplayMember = "branchName";
                lstbCustomers.ValueMember = "branchId";
            }
            else
            {
                lstbCustomers.Items.Add("There are no branches defined for the selected customer.");
                lstbCustomers.Refresh();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            dbContext.Dispose();
        }
    }

I have no idea what I'm doing incorrectly. I keep having "A constant value of type "System.Object" could not be created. In this situation, only basic types (such Int32, String, and Guid) are supported." dreams.

1
93
1/4/2011 10:05:51 AM

Accepted Answer

Use == rather than Equals:

where t.CustID == custIdToQuery

You could discover that this doesn't build if the types are wrong.

229
1/4/2011 10:08:24 AM

Popular Answer

A nullable int caused the same problem for me. Instead, using == works well, but if you wish to use. Equals allows you to compare a value to the nullable variable's value, so

where t.CustID.Value.Equals(custIdToQuery)


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow