使用实体框架连接查询 [英] Join Query using Entity FrameWork

查看:130
本文介绍了使用实体框架连接查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用
选择用户记录

I trying to select user record using

var customUser = (from u in context.Users
            join pr in context.PasswordRecoveries on u.Id equals pr.userId
            where pr.url == token && pr.requestDateTime.AddHours(12) <DateTime.Now
            select u).First();




此查询出了什么问题?
请帮助我.




Whats wrong in this query?
Please Help me.

推荐答案

您需要告诉我们遇到的错误,但是EF不喜欢其中的函数.改为执行以下操作:

You need to tell us what errors you get, but EF does not like functions inside it. Do this instead:

DateTime dt = DateTime.Now.AddHours(-12);

var customUser = (from u in context.Users
            join pr in context.PasswordRecoveries on u.Id equals pr.userId
            where pr.url == token && pr.requestDateTime < dt

            select u).First()



然后,如果仍然无法解决问题,请告诉我们您遇到什么错误,以便我们进一步为您提供帮助.

如果不一定总能找到一个值,也可以使用FirstOrDefault().如果您使用的是"first",那么还应该使用一个顺序,并且可能有多个记录,否则您得到的记录基本上是随机的.



Then if it still does not work, tell us what error you get, so we can help you further.

You can also use FirstOrDefault() if it won''t always find a value. You should also use an order by if you''re using ''first'' and there could be more than one record, or the one you get will be essentially random.


//Set date out of query to compare
DateTime DateToCompare = DateTime.Now.AddHours(-12);

//Use FirstOrDefault(), it will return null value or only one record based on data
var customUser = (from u in context.Users
                join pr in context.PasswordRecoveries on u.Id equals pr.userId
                where pr.url == token && pr.requestDateTime < DateToCompare 
                select u).FirstOrDefault();
if(customUser != null)
{
//Success code
}


我建​​议以存储过程的形式使用sql语句.它将为您提供更好的性能.另一点是,与linq语句相比,对sql语句进行故障排除总是很容易.

有关如何在实体框架中使用存储过程的逐步说明,请查看本文:

如何在实体框架中使用存储过程 [
I would suggest that use sql statements in the form of stored procedures. It will give you better performance. Another point is that its always easy to troubleshoot sql statements than linq statements.

For step by step instructions on how to use stored procedures in entity framework, check this article:

How to use Stored Procedures in Entity Framework[^]


这篇关于使用实体框架连接查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆