allencoded
allencoded

Reputation: 7265

MVC error working with a List getting Object not set to an instance of an object

I am getting an error I can't figure out how to fix? It claims to be happening on:

var respondents = RespondentRepository.GetRespondents(UserSession, fieldsToInclude).Where(r=>r.Email.Contains(query)).ToList();

When I remove all the .Where stuff it appears to work fine. I am not really use to this error so I am not sure where the best start would be?

Error:

System.NullReferenceException: Object reference not set to an instance of an object.

Code:

MakeSafeRequest(() =>
                {
                    var respondents = RespondentRepository.GetRespondents(UserSession, fieldsToInclude).Where(r=>r.Email.Contains(query)).ToList();

                    model = new RespondentSearchViewModel
                    {
                        Respondents = respondents,

                        TableData = respondents.SelectToListOrEmpty(r =>
                        {
                            return new TableRowViewModel
                            {
                                Id = r.Id,
                                Data = new Dictionary<string, string>
                                {
                                    { "FirstName", r.FirstName },
                                    { "LastName", r.LastName },
                                    { "EmailAddress", r.Email },
                                    { "Project", r.ProjectId.ToString() },
                                    { "Status", r.RecruitingStatus.ToIconHtml() },
                                    { "ViewHistory", "<div class=\"btnBlue btSml\"><a class=\"closeMe\" href=\"/RespondentSearch/RespondentDetails/?respondentId="+r.Id +"\" >view detail</a></div>"}
                                    //{ "StatusDate", r.LastActionDate.Value.ToLocalTime().ToString() },
                                }
                            };
                        })
                    };
                });

MODEL:

public class RespondentSearchViewModel:ListPageViewModel
    {
        public List<Respondent> Respondents { get; set; }
    }

Upvotes: 0

Views: 64

Answers (1)

Daniel Gabriel
Daniel Gabriel

Reputation: 3985

r.Email might be null. Try changing your lambda to:

r => (r.Email == null ? false : r.Email.Contains(query))

Upvotes: 1

Related Questions