不能对表达式应用与[]的索引 [英] cannot apply indexing with [] to an expression

查看:149
本文介绍了不能对表达式应用与[]的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 var dbPerson = from p in db.People 
                where p.Id == PersonId select p;
 dbPerson[0].HolidaysRemaining--;

在dbPerson [0]中抛出一个错误,表示不能使用[]将索引应用于键入'system.linq.lqueryable,holidayBookingApp.model.person>

is throwing me an error with dbPerson[0] saying cannot apply indexing with [] to an expression of type 'system.linq.lqueryable,holidayBookingApp.model.person>

有人可以告诉我如何解决这个问题?

can someone please advise how I can resolve this?

谢谢

推荐答案

要获取您的查询的第一个项目 dbPerson return,use

To get the first item that your query dbPerson returns, use

var firstPerson = dbPerson.First();

单个如果您只希望一场比赛并希望在这个期望被破坏的情况下抛出异常。

or Single if you only expect one match and want an exception to be thrown if this expectation is broken.

但是,我不相信 firstPerson.HolidaysRemaining - ; 将更改数据库中的任何内容,而不需要进一步的代码:

However, I'm not convinced firstPerson.HolidaysRemaining--; will change anything in your database without further code:

var dbPeopleWithThisId = from p in db.People 
                         where p.Id == PersonId
                         select p;
var specificPerson = dbPeopleWithThisId.Single();
specificPerson.HolidaysRemaining--;
db.SaveChanges(); // Thanks to J. Steen

这篇关于不能对表达式应用与[]的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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