Tyler Durden
Tyler Durden

Reputation: 2171

Foreach in null

I have this model class:

public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }

    public DbSet<ForeignExpression> learnedexpressions { get; set; }
}

I create the dbset in the controller:

int userID = (int)Membership.GetUser().ProviderUserKey;
model.ForeignExpressions=db.UserProfiles.Find(userID).learnedexpressions;

Then in the view, I try to write them out:

@foreach (var exp in Model.ForeignExpressions.OrderByDescending(m => m.dateAdded).Take(@numOfExpressions).ToList().OrderBy(m => m.dateAdded))
{
<tr>
<td> @exp.expression</td>
<td> @exp.meaning</td>
<td> "@exp.context"</td>
<td> @exp.dateAdded</td>
</tr>  
}

However, Model.ForeignExpressions is null, so I get a runtime error for the foreach (Value cannot be null). I suspect that it's because I don't have any ForeignExpression yet for the current user, so the value of learnedexpressions is null. Am I correct, and what is the best way to handle this? Should I fix it in the view, the controller, or the model?

Upvotes: 0

Views: 138

Answers (2)

user1548266
user1548266

Reputation:

Test whether ForeignExpressions is null prior to attempting to use it:

@if (Model.ForeignExpressions != null)
{
 // foreach
}

Upvotes: 1

Moho
Moho

Reputation: 16498

Make the learnedespressions property virtual so as to allow lazy loading of the collection and change the type of the property from DbSet<T> to ICollection<T>

Upvotes: 1

Related Questions