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

时间:2014-06-12 20:23:35

标签: c# asp.net-mvc entity-framework asp.net-mvc-5 entity-framework-6

我不太理解为什么我在MVC5 / EF6 / Code First Migrations应用中遇到此错误。我试图(在我的用户列表中)显示组织的[名称]或用户当前与之关联的赞助商的[名称]。我在 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; }

这是我目前正在使用的索引视图:

@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>

我之前尝试columns.Add().Encoded(false).Sanitized(false).RenderValueAs(f => Html.Raw(s => s.Organization.Name));,但段s => s.Organization.Name仍然导致Cannot convert lambda expression to type 'object' because it is not a delegate type

据我所知,我的代码行columns.Add().Encoded(false).Sanitized(false).RenderValueAs(o => o.Organization.ToString()).Titled("MemOrg.").Sortable(true).Filterable(true).SetWidth(25);应该能够正确呈现[Name](在Model中指定显示为&#34; Organization&#34;),但是当View加载时我收到了Object reference not set to an instance of an object.

任何人都可以解释我做错了什么吗?

修改: 我已经想出[User.Organization](MemberOrganizations.Name)&amp; [User.Sponsor](SponsorOrganizations.Name)确实从我的控制器传递为null。为了解决这个问题,我并不是试图遍历我的<ApplicationUser>列表并查询相应的表格以填充当前的空值。

这是我到目前为止所做的:

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

在第一个用户处,user.Sponsor属性最终成为:

 ?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"

如何将Name属性专门从db.SponsorOrganizations.Find(user.SponsorOrgId)转换为user.Sponsor

1 个答案:

答案 0 :(得分:1)

IdentityModels.cs 中未正确命名外键属性。外键属性必须与导航属性的名称匹配,或者您需要使用[ForeignKey]属性。

应该是:

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

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

或:

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

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

或:

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

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

由于您将外键标记为未映射,因此SponsorOrganizations可能也存在一些问题。