![](/img/trans.png)
[英]Linq to Entities - “Unable to create a constant value of type 'System.Object'…”
[英]Linq Query keeps throwing “Unable to create a constant value of type System.Object…”, Why?
以下是代码示例:
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’)。”
使用 == 代替 Equals:
where t.CustID == custIdToQuery
如果类型不正确,您可能会发现它无法编译。
我对可为空的 int 有同样的问题。 改用 == 效果很好,但如果你想使用 .Equals,你可以将它与可空变量的值进行比较,所以
where t.CustID.Value.Equals(custIdToQuery)
当我尝试使用可空的小数执行 .Equals 时,我遇到了同样的问题。 改用 == 效果很好。 我想这是因为它没有试图匹配十进制的确切“类型”? 到十进制。
我遇到了同样的问题,我正在将集合对象"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))
就我而言,我将(sender as Button).Text
的直接调用更改(sender as Button).Text
使用临时(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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.