Linq Query continues to throw "Cannot create a constant value of type System.Object ....", Why?

The following is sample code:

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 cannot understand what I am doing wrong. I keep getting β€œUnable to create a constant value of typeβ€œ System.Object. ”Only primitive types (such as Int32, String, and Guid) are supported in this context.

+68
c # linq winforms entity-framework
Jan 04 2018-11-11T00:
source share
4 answers

Use == instead of Equals:

 where t.CustID == custIdToQuery 

If the types are incorrect, you may find that this is not compiled.

+159
Jan 04 2018-11-11T00:
source share

I had the same problem with nullable int. Using == instead works beautifully, but if you want to use .Equals, you can compare it with the value of the NULL variable, so

 where t.CustID.Value.Equals(custIdToQuery) 
+20
Jul 17 '13 at 20:30
source share

I had the same problem when I tried to do .Equals with a zero decimal. Using == instead works beautifully. I think this is because he is not trying to match the exact "type" of the decimal number? to decimal.

+7
Nov 15 '12 at 18:07
source share

I ran into the same problem and I compared the Collection Object "User" with the integer data type "userid" ( x.User.Equals(userid) )

 from user in myshop.UserPermissions.Where(x => x.IsDeleted == false && x.User.Equals(userid)) 

and the correct request is x.UserId.Equals(userid)

 from user in myshop.UserPermissions.Where(x => x.IsDeleted == false && x.UserId.Equals(userid)) 
-one
Nov 10 '17 at 7:34 on
source share



All Articles