MVC5: Object reference not set to an instance of an object?

asp.net-mvc asp.net-mvc-5 c# entity-framework entity-framework-6

Question

I'm not quite following why I am getting this error in my MVC5/EF6/Code First Migrations app. I am attempting to (in my list of Users) display the [Name] of the Organization or [Name] of the Sponsor the User is currently associated with. I have the following properties defined in my IdentityModels.cs:

    [GridColumn(Title = "Org.", SortEnabled = true, Width = "100")]
    public int? MemberOrgId { get; set; }

    [NotMappedColumn]
    public int? SponsorOrgId { get; set; }

    [NotMappedColumn]
    public virtual MemberOrganizations Organization { get; set; }

    [NotMappedColumn]
    public virtual SponsorOrganizations Sponsor { get; set; }

MemberOrganizations.cs:

    [Required]
    [Display(Name = "Organization")]
    public string Name { get; set; }

    [Display(Name = "Users:")]
    public virtual ICollection<ApplicationUser> Users { get; set; }

SponsorOrganizations.cs:

    [Required]
    [Display(Name="Name")]
    public string Name { get; set; }

    [Display(Name = "Users:")]
    public virtual ICollection<ApplicationUser> Users { get; set; }

This is the Index View I am currently working with:

@using GridMvc.Html
@model IEnumerable<PROJECTS.Models.ApplicationUser>

@{
    ViewBag.Title = "View Users";
    Layout = "~/Areas/Admin/Views/Shared/_LayoutAdmin.cshtml";

}

<div class="overflowPrevention">
    <!-- Grid.MVC Code -->
    <div>

        @Html.Grid(Model).Columns(columns =>
        {
            columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => Html.ActionLink("Edit", "Edit", "UserManagement", new { id = o.Id }, null)).SetWidth(15);
            columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => o.Name).Titled("Name").Sortable(true).Filterable(true).SetWidth(100);
           columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => o.Position).Titled("Position").Sortable(true).Filterable(true).SetWidth(50);
            columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => o.Email).Titled("Email").Sortable(true).Filterable(true).SetWidth(100);
            columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => o.EmailConfirmed.ToString()).Titled("Confirmed").Sortable(true).Filterable(true).SetWidth(100);
            // VALUE TRYING TO RENDER
            columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => o.Organization.ToString()).Titled("MemOrg.").Sortable(true).Filterable(true).SetWidth(25);
            // BELOW CORRECTLY RENDERS THE MEMBER ORG ID 
            columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => o.MemberOrgId.ToString()).Titled("MemOrg.").Sortable(true).Filterable(true).SetWidth(25);
            // BELOW CORRECTLY RENDERS THE SPONSOR ID 
            columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => o.SponsorOrgId.ToString()).Titled("Sponsor").Sortable(true).Filterable(true).SetWidth(25);
        }).WithPaging(5)
    </div>
</div>

I was previously attempting columns.Add().Encoded(false).Sanitized(false).RenderValueAs(f => Html.Raw(s => s.Organization.Name)); but the segment s => s.Organization.Name kept resulting in Cannot convert lambda expression to type 'object' because it is not a delegate type.

As far as I can tell, my code line columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => o.Organization.ToString()).Titled("MemOrg.").Sortable(true).Filterable(true).SetWidth(25); should be able to correctly render the [Name] (specified in Model to display as "Organization"), but when the View loads I receive Object reference not set to an instance of an object.

Can anyone explain what it is that I am doing incorrect?

EDIT: I have figured out that [User.Organization] (MemberOrganizations.Name) & [User.Sponsor] (SponsorOrganizations.Name) are indeed being passed from my controller as being null. To remedy this, I am no attempting to Loop through my list of <ApplicationUser>'s and query the appropriate tables in order to fill the currently null value.

This is what I have so far:

    // GET: Admin/UserManagement
    public async Task<ActionResult> Index()
    {
        ViewBag.headerTitle = "User Management";
        ViewBag.showCreateButton = true;
        ViewBag.createUrl = "/Admin/UserManagement/Create";
        ViewBag.createText = " Create a New User";
        List<ApplicationUser> model = UserManager.Users.ToList();
        foreach (ApplicationUser user in model)
        {
            if (user.MemberOrgId != null)
            {
                user.Organization = db.MemberOrganizations.Find(user.Organization);

            }
            if (user.SponsorOrgId != null)
            {
                user.Sponsor = db.SponsorOrganizations.Find(user.SponsorOrgId);
            }
        }
        return View(model);
    }

Breaking at the first user, user.Sponsor property ends up being:

 ?user.Sponsor
    {System.Data.Entity.DynamicProxies.SponsorOrganizations_F2A27693F33AFF36C814F6FFA2CE63AD656938244F599B7D1AB2ED80CC26EF9A}
    [System.Data.Entity.DynamicProxies.SponsorOrganizations_F2A27693F33AFF36C814F6FFA2CE63AD656938244F599B7D1AB2ED80CC26EF9A]: {System.Data.Entity.DynamicProxies.SponsorOrganizations_F2A27693F33AFF36C814F6FFA2CE63AD656938244F599B7D1AB2ED80CC26EF9A}
    City: null
    Country: null
    Enabled: true
    FacebookUrl: "https://www.facebook.com/sponsor1"
    Id: 1
    LogoSrc: "Sponsor1.jpg"
    Name: "Sponsor1"
    OwnerId: "1d720c20-a508-4880-a5e6-80af5f2f8caf"
    OwnerName: "Sponsor Primary"
    ProfilePictureUrl: "sponsorprofilepicture/Sponsor1.jpg"
    SponsorServiceCategory: Count = 11
    State: null
    TwitterUrl: "https://twitter.com/sponsor1"
    Users: Count = 0
    WebsiteUrl: "http://www.sponsor1.com"

How do I get the Name property specifically from db.SponsorOrganizations.Find(user.SponsorOrgId) into user.Sponsor?

1
2
9/5/2014 5:56:50 AM

Popular Answer

The foreign key properties are not named correctly in IdentityModels.cs. The foreign key properties must match with the navigation property's name or you need to use the [ForeignKey] attribute.

Should be:

[GridColumn(Title = "Org.", SortEnabled = true, Width = "100")]
public int? OrganizationId { get; set; }

[NotMappedColumn]
public virtual MemberOrganizations Organization { get; set; }

or:

[GridColumn(Title = "Org.", SortEnabled = true, Width = "100")]
public int? MemberOrgId { get; set; }

[ForeignKey("MemberOrgId")
[NotMappedColumn]
public virtual MemberOrganizations Organization { get; set; }

or:

[ForeignKey("Organization")
[GridColumn(Title = "Org.", SortEnabled = true, Width = "100")]
public int? MemberOrgId { get; set; }

[NotMappedColumn]
public virtual MemberOrganizations Organization { get; set; }

There might be some problems with SponsorOrganizations too since you have marked the foreign key as unmapped.

1
12/4/2014 8:50:06 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow