使用"让" kewword在LINQ查询与EF 4.3 [英] Using the "let" kewword in a LINQ Query with EF 4.3

查看:166
本文介绍了使用"让" kewword在LINQ查询与EF 4.3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有简单的LINQ问题,我想不通。 我有一个表用户和表员工一个用户可以有0,...,N员工。

我希望做这样的事情:

  VAR的结果=从u在context.users
             其中,u.UsrId = 2
             令e = u.Employees.First()
             选择新
{
  用户ID = u.UsrId,
  名字= e.FirstName
};
 

当然,这并不工作becasue的一()电话是违法的。首先()只能付出的结束选择。 什么也没有工作是选择像这样一个previous查询员工:

  VAR员工=来自厂商。在context.Employees .....
 

...然后说让E =员工而不是令e = u.Employees()。首先()

我不知道,如果使用让正确的。我认为这是子查询。

的原因一()电话是在雇员表不应该为每一个用户的多个条目。这是设计中的错误,我必须处理它了。所以,我只是想第一个。

在context.users
解决方案

  VAR的结果=从u
令e = u.Employees.FirstOrDefault(X => x.bossId == u.UsrId)
其中,u.UsrId = 2
选择新{用户ID = u.UsrId,名字= e.FirstName};
 

无测试只是一个TIPP。

I have simple LINQ problem that I can't figure out. I have a table Users and a table Employees. One User can have 0...n employees.

I'd like to do something like this:

var result = from u in context.users
             where u.UsrId = 2
             let e = u.Employees.First()
             select new 
{
  UserId = u.UsrId,
  FirstName = e.FirstName
};

That does not work of course becasue the First() call is illegal. First() can only come at the end of a select. What also did not work is to select the employee in a previous query like so:

var employee = from e. in context.Employees.....

...and then say let e = employee instead of let e = u.Employees().First()

I am not sure if the use of let correct. I thought it is for subqueries.

The reason for the First() call is that the Employees table should not have more than one entry for each user. That is a mistake in the design and I have to deal with it now. So I just want the first one.

解决方案

var result = from u in context.users
let e = u.Employees.FirstOrDefault(x => x.bossId == u.UsrId)
where u.UsrId = 2
select new  {   UserId = u.UsrId,   FirstName = e.FirstName }; 

Just a tipp without test.

这篇关于使用"让" kewword在LINQ查询与EF 4.3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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