Nee*_*eel 92 .net c# linq entity-framework winforms
以下是代码示例:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我无法理解我做错了什么.我一直得到"无法创建类型'System.Object'的常量值.在此上下文中仅支持原始类型(例如Int32,String和Guid')."
Mar*_*ers 224
使用==而不是等于:
where t.CustID == custIdToQuery
Run Code Online (Sandbox Code Playgroud)
如果类型不正确,您可能会发现这不能编译.
klo*_*eek 28
我有一个可以为null的int的问题.使用==代替很好,但如果你想使用.Equals,你可以将它与可空变量的值进行比较,所以
where t.CustID.Value.Equals(custIdToQuery)
Run Code Online (Sandbox Code Playgroud)
当我试图做的时候我遇到了同样的问题.带有可空小数的等值.使用==代替很好地工作.我想这是因为它不是试图匹配十进制的确切"类型"?到十进制.