zinon
zinon

Reputation: 4664

Cannot apply indexing with [] to an expression of type '<anonymous type:?

I have created the following table:

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]

I'm trying to retrieve data from this table and add them to dictionary.

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);

In the last code line I get the following error:

Error CS0021 Cannot apply indexing with [] to an expression of type '<anonymous type: ? rescuer_info, ? amb_plates_1, ? amb_plates_2>'

Upvotes: 0

Views: 239

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415715

You asked for the First or default record. There's no array or collection, there is no [0] item. It's just call_info_extra.rescuer_info (assuming you have a result at all). If there's no record, the OrDefault part of the name means you get the default null value for a reference type, and then the expression will produce a NullReferenceException trying to lookup the rescuer_info property from that null reference.

Upvotes: 1

Related Questions