简体   繁体   English

无法在LINQ to EF查询中创建常量值

[英]Unable to create a constant value in LINQ to EF query

I am trying to retrieve data from a user class webpages_membership for verifying a token password change. 我正在尝试从用户类webpages_membership检索数据以验证令牌密码更改。

Wehn I try to run this query to get the necessary information from the database: 我试图运行此查询以从数据库中获取必要的信息:

bool any = ttf.webpages_Membership
    .Any(x => x.UserId.Equals(userid)
         && x.PasswordVerificationToken == rt
         && x.PasswordVerificationTokenExpirationDate < DateTime.Now);

if (any == true) {

}

I get this exception 我得到这个例外

Unable to create a constant value of type 'DBContext.Models.Customers'. 无法创建类型为'DBContext.Models.Customers'的常量值。 Only primitive types or enumeration types are supported in this context. 在此上下文中仅支持原始类型或枚举类型。

How can I avoid that exception? 如何避免该异常?

Use this, to ensure that the LINQ expression only have constant values. 使用它来确保LINQ表达式仅具有常量值。 Do also use == instead of .Equals (I'm not sure if .Equals can be correctly processed by LINQ. Perhaps it's possible, but I'm sure that == works fine). 也请使用==代替.Equals (我不确定LINQ是否可以正确处理.Equals 。也许可以,但是我确定==可以正常工作)。

var now = DateTime.Now;

ttf.webpages_Membership
    .Any(x => x.UserId == userid && 
         x.PasswordVerificationToken == rt &&
         x.PasswordVerificationTokenExpirationDate < now);

LINQ examines the expression tree of the lambda predicate, and can transfer constant values to the server. LINQ检查lambda谓词的表达式树,并可以将常量值传输到服务器。 I think it doesn't treat DateTime.Now as a constant, unless you capture it in a variable as shown. 我认为它不会将DateTime.Now视为常量,除非您如图所示将其捕获到变量中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 NotSupportedException:无法在LINQ查询中创建常量值 - NotSupportedException: Unable to create constant value in LINQ query 无法在linq查询中创建常量值 - Unable to create a constant value in a linq query 在使用Linq编辑EF时,无法创建常量的类型值 - Unable to create a constant value of type while editing User in EF with Linq LINQ语句无法创建类型的常量值 - LINQ statement unable to create a constant value of type Linq错误:无法创建类型的常量值 - Linq error: Unable to create a constant value of type LINQ-“无法创建类型[type]的常量值”? - LINQ - “Unable to create constant value of type [type]”? 无法创建类型“”的常量值。 在此上下文中仅支持原始类型或枚举类型。 ASP.NET MVC LINQ EF - Unable to create a constant value of type ''. Only primitive types or enumeration types are supported in this context. ASP.NET MVC LINQ EF 使用GroupBy的LINQ查询导致“无法创建类型&#39;System.Object&#39;的常量值...” - LINQ query with GroupBy causing “Unable to create a constant value of type 'System.Object'…” LINQ查询错误:无法创建类型的常量值。 在此上下文中仅支持原始类型或枚举类型 - LINQ Query error: Unable to create a constant value of type. Only primitive types or enumeration types are supported in this context LINQ查询从分组中查找最小值-无法创建类型&#39;X&#39;的常量 - LINQ Query to find minumum value from a grouping - unable to create constant of type 'X'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM