MVC5:对象引用没有设置为对象的实例?

时间:2022-10-22 16:58:13

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:

我不太明白为什么我在MVC5/EF6/Code First Migrations app中会出现这个错误。我正在尝试(在我的用户列表中)显示用户当前关联的组织的[名称]或[名称]。在我的标识模型中定义了以下属性。

    [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:

MemberOrganizations.cs:

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

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

SponsorOrganizations.cs:

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.

我之前尝试过使用column . add (). encoded (false). saniated (false)。RenderValueAs(f = > Html。生(s = > s.Organization.Name));但分段s =>。不能将lambda表达式转换为“object”类型,因为它不是委托类型。

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.

就我所知,我的代码行。add (). encoded(错误). saniated(错误)。RenderValueAs(o = > o.Organization.ToString()).Titled(“MemOrg”).Sortable(真正的).Filterable(真正的).SetWidth(25);应该能够正确地呈现[名称](在模型中指定为“组织”),但是当视图加载时,我接收的对象引用没有设置为对象的实例。

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.

编辑:我找到了[用户]。组织](MemberOrganizations.Name)&(用户。赞助商](赞助机构。名称)从我的控制器中传递为null。为了解决这个问题,我没有试图循环遍历 's的列表,并查询适当的表以填充当前的空值。

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?

我如何从db. sponsor organization .查找(user.SponsorOrgId)到user.Sponsor中获得名称属性?

1 个解决方案

#1


1  

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.

在identitymodel .cs中不能正确地命名外键属性。外键属性必须与导航属性的名称匹配,或者需要使用[ForeignKey]属性。

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.

由于您已经将外键标记为unmapping,所以赞助组织也可能存在一些问题。

#1


1  

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.

在identitymodel .cs中不能正确地命名外键属性。外键属性必须与导航属性的名称匹配,或者需要使用[ForeignKey]属性。

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.

由于您已经将外键标记为unmapping,所以赞助组织也可能存在一些问题。