该名称在当前上下文中不存在(在 MVC Entity Framework 的 ActionResult 中)

The name does not exist in the current context (in ActionResult with MVC Entity Framework)

在我拥有的控制器的 ActionResult "Details(int? id)" 中(在 ActionResult 中,这是在一个条件内:if (User.Identity.IsAuthenticated) { bla, bla):

            var TheUser = db.AspNetUsers.Where(u => u.Id == CurrentUser)
                         .Select(u => new
                         {
                             ID = u.Id,
                             Email = u.Email,
                             Username = u.UserName,
                             Surrname = u.Surname,
                             Name = u.Name,
                             Role = u.Role,
                             CreditBalance = u.CreditBalance
                         }).Single();

            var TheJournal = db.CreditJournal.Where(tj => tj.CvID == id && tj.UseBy == CurrentUser)
                            .Select(tj => new
                               {
                                   IdJournal = tj.IdJournal,
                                   Operation = tj.Operation,
                                   CvID = tj.CvID,
                                   CreditConsumed = tj.CreditConsumed,
                                   UseDate = tj.UseDate,
                                   UseBy = tj.UseBy
                               });

            var Counter = TheJournal.Count();

当我在调试模式下评估值时,我有:

TheUser |>>>    { ID = "56cc2430-4db5-4799-ad41-fa1d103d1967", Email = "sales@maps4u.ro", Username = "sales@maps4u.ro", Surrname = "Laurentiu", Name = "LAZAR", Role = 3, CreditBalance = 75 }  <Anonymous Type>

TheJournal |>>> {System.Data.Entity.Infrastructure.DbQuery<<>f__AnonymousType9<int,string,int?,int?,System.DateTime?,string>>}  System.Linq.IQueryable<<>f__AnonymousType9<int,string,int?,int?,System.DateTime?,string>> {System.Data.Entity.Infrastructure.DbQuery<<>f__AnonymousType9<int,string,int?,int?,System.DateTime?,string>>}

Counter |>>>    The name 'Counter' does not exist in the current context

上面显示的简单代码有什么问题? (对于给定条件,TheJornal returns 的等效 SQL 语句,至少 4 条记录)。 我想以某种方式在条件之外声明变量,但它们必须是什么类型? (无论如何,第一个 TheUser 还可以,问题从第二个 TheJournal 开始)

为您的 TheJournal 查询使用 .ToList()。然后使用 Count 获取计数器 -

var Counter = TheJournal.Count