Html.DisplayFor 通过其他查询 table 返回空字符串
Html.DisplayFor query through other table returning an empty string
我在尝试弄清楚如何使用 ASP.Net Identity 创建用户配置文件时遇到了障碍。我的数据库设置如下
this,其中 Id
在 AspNetUsers
的外键 table UserPages
。
我正在使用标准代码将模型交付给视图:
public ActionResult View(string id)
{
UserPage userPage = db.UserPages.Find(id);
(...)
return View(userPage);
}
我的模特:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.WebPages.Html;
namespace Citrus.Models
{
public class UserPage
{
[Key]
public string Id { get; set; }
[ForeignKey("Id")]
public ApplicationUser User { get; set; }
public string AboutMe { get; set; }
public string AvailableTime { get; set; }
}
}
然后在视图中我可以使用
@Html.DisplayFor(model => model.AboutMe)
在数据库 UserPages
中显示 属性 AboutMe
。但是当我尝试通过模型从 AspNetUsers
获取数据时:
@Html.DisplayFor(model => model.User.Name)
我只得到一个空字符串。 User.Name
不可为空,并且该条目存在于数据库中。方法返回为空是什么原因,如何解决?
事实证明,我从未将 AspNetUsers
包含到 UserPages
查询中。
UserPage userPage = db.UserPages.Find(id);
用以下代码替换我的查询可以解决问题:
UserPage userPage = db.UserPages.Include(x => x.User).Where(x => x.Id == id).FirstOrDefault()
我现在可以使用 @Html.DisplayFor(model => model.User.Property)
获取用户的任何 属性
我在尝试弄清楚如何使用 ASP.Net Identity 创建用户配置文件时遇到了障碍。我的数据库设置如下
this,其中 Id
在 AspNetUsers
的外键 table UserPages
。
我正在使用标准代码将模型交付给视图:
public ActionResult View(string id)
{
UserPage userPage = db.UserPages.Find(id);
(...)
return View(userPage);
}
我的模特:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.WebPages.Html;
namespace Citrus.Models
{
public class UserPage
{
[Key]
public string Id { get; set; }
[ForeignKey("Id")]
public ApplicationUser User { get; set; }
public string AboutMe { get; set; }
public string AvailableTime { get; set; }
}
}
然后在视图中我可以使用
@Html.DisplayFor(model => model.AboutMe)
在数据库 UserPages
中显示 属性 AboutMe
。但是当我尝试通过模型从 AspNetUsers
获取数据时:
@Html.DisplayFor(model => model.User.Name)
我只得到一个空字符串。 User.Name
不可为空,并且该条目存在于数据库中。方法返回为空是什么原因,如何解决?
事实证明,我从未将 AspNetUsers
包含到 UserPages
查询中。
UserPage userPage = db.UserPages.Find(id);
用以下代码替换我的查询可以解决问题:
UserPage userPage = db.UserPages.Include(x => x.User).Where(x => x.Id == id).FirstOrDefault()
我现在可以使用 @Html.DisplayFor(model => model.User.Property)