以下是代码示例:
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();
}
}
我无法理解我做错了什么。我一直在“无法创建类型'System.Object'的常量值。在此上下文中仅支持基本类型(例如Int32,String和Guid')。”
答案 0 :(得分:213)
使用==而不是等于:
where t.CustID == custIdToQuery
如果类型不正确,您可能会发现这不能编译。
答案 1 :(得分:27)
我遇到了与nullable int相同的问题。使用==代替很好,但如果你想使用.Equals,你可以将它与可空变量的值进行比较,所以
where t.CustID.Value.Equals(custIdToQuery)
答案 2 :(得分:8)
当我尝试做的时候,我遇到了同样的问题。带有可空小数的等式。使用==代替很好地工作。我想这是因为它不是试图匹配十进制的确切“类型”?到十进制。
答案 3 :(得分:0)
我遇到了同样的问题,我正在将Collection Object "User"
与整数数据类型"userid"
(x.User.Equals(userid)
)进行比较
from user in myshop.UserPermissions.Where(x => x.IsDeleted == false && x.User.Equals(userid))
并且正确的查询是x.UserId.Equals(userid)
from user in myshop.UserPermissions.Where(x => x.IsDeleted == false && x.UserId.Equals(userid))
答案 4 :(得分:0)
在我的情况下,我将使用临时变量的(sender as Button).Text
的直接调用更改为间接调用已奏效。
工作代码:
private void onTopAccBtnClick(object sender, EventArgs e)
{
var name = (sender as Button).Text;
accountBindingSource.Position =
accountBindingSource.IndexOf(_dataService.Db.Accounts.First(ac => ac.AccountName == name));
accountBindingSource_CurrentChanged(sender, e);
}
儿童车代码:
private void onTopAccBtnClick(object sender, EventArgs e)
{
accountBindingSource.Position =
accountBindingSource.IndexOf(_dataService.Db.Accounts.First(ac => ac.AccountName == (sender as Button).Text));
accountBindingSource_CurrentChanged(sender, e);
}