我很难获得LINQ语法..如何以更好的方式执行此命令?
var user = (from u in context.users
where u.email.Equals(email)
select u).Single();
var pinToUser = (from ptu in context.pintousers
where ptu.user_id.Equals(user.id)
select ptu).Single();
var pin = (from p in context.pins
where p.idpin.Equals(pinToUser.pin_idpin)
select p).Single();
return pin;
Run Code Online (Sandbox Code Playgroud)
如您所见,有一个表用户,一个表pintouser和一个表针.Pintouser引用用户和引脚.是否有可能写一些像"user.pintouser.pin"这样的短片?我想我已经设置了导航属性,但我不确定如何正确使用它们,或者我是否可以通过修改它们来使它们更好.
谢谢阅读
使用联接将所有内容重写为单个干净查询.如果我正确地阅读了您的查询,这应该会给您正确的结果:
var pin = (from u in context.users
join ptu in context.pintousers on u.id equals ptu.user_id
join p in context.pins on ptu.pin_idpin equals p.idpin
where u.email == email
select p).Single();
Run Code Online (Sandbox Code Playgroud)
但请记住,如果此查询返回除单个结果之外的任何内容,则代码将抛出异常.
如果你想处理获得一行或没有行的可能性,那么你应该使用SingleOrDefault().
如果你想处理获取任意数量行的可能性,那么你应该真正使用它FirstOrDefault().
| 归档时间: |
|
| 查看次数: |
231 次 |
| 最近记录: |