【问题标题】:Cannot apply indexing with [] to an expression of type '<anonymous type:?无法将带有 [] 的索引应用于类型为 '<anonymous type:?
【发布时间】:2021-02-15 22:49:41
【问题描述】:

我创建了下表:

CREATE TABLE [dbo].[Call_Info_extra](
    [Call_Info_extra_id] [int] IDENTITY(1,1) NOT NULL,
    [nurse_account_login_id] [int] NOT NULL,
    [rescuer_info] [nvarchar](255) NULL,
    [amb_plates_1] [nvarchar](50) NULL,
    [amb_plates_2] [nvarchar](50) NULL,

 CONSTRAINT [PK_Call_Info_extra_constr] PRIMARY KEY CLUSTERED 
(
    [Call_Info_extra_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

我正在尝试从此表中检索数据并将它们添加到字典中。

var call_info_extra = entities.Call_Info_extra.Where(c => c.nurse_account_login_id == query[0].nurse_account_login_id).Select(c => new { c.rescuer_info, c.amb_plates_1, c.amb_plates_2 }).FirstOrDefault(); ;
IDictionary<string, string> myNurseAccount = new Dictionary<string, string>();
myNurseAccount.Add("rescuer_info", call_info_extra[0].rescuer_info);

在最后一行代码中出现以下错误:

错误 CS0021 无法将带有 [] 的索引应用到类型为“'

【问题讨论】:

  • 您要求提供 First 或默认记录。没有数组或集合,没有[0] 项。我只是call_info_extra.rescuer_info(假设你有结果)
  • @JoelCoehoorn 谢谢!就是这样。将其添加为接受它的答案。
  • @JoelCoehoorn 如果我没有结果,这将是Null 值,对吧?

标签: sql-server asp.net-mvc


【解决方案1】:

您要求第一个或默认记录。没有数组或集合,没有[0] 项。这只是call_info_extra.rescuer_info(假设你有一个结果)。如果没有记录,名称的OrDefault 部分意味着您获得了引用类型的默认null 值,然后表达式将产生NullReferenceException 尝试从该rescuer_info 查找null 属性参考。

【讨论】:

    猜你喜欢
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    • 2011-04-06
    • 2019-03-20
    • 1970-01-01
    相关资源
    最近更新 更多