我有一个名为RegisterViewModel的视图模型 -
public class RegisterViewModel
{
public string UserName { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
和两个名为User和UserDetails的模型
public class User
{
[Key]
public string UserName { get; set; }
public string Email { get; set; }
public virtual ICollection<Role> Roles { get; set; }
public virtual UserDetails UserDetails { get; set; }
}
public class UserDetails
{
[Key]
public string UserName { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
[Required]
public virtual User User { get; set; }
}
在我的用户控制器中,我的详细信息方法有以下内容 -
public ViewResult Details(string id)
{
User user = context.Users
.Include (i => i.UserDetails)
.Where(i => i.UserName == id)
.Single();
user.UserDetails = new UserDetails();
RegisterViewModel viewModel = new RegisterViewModel{
UserName = user.UserName,
FirstName = user.UserDetails.FirstName,
LastName = user.UserDetails.LastName,
Salary = user.UserDetails.Salary,
Email = user.Email,
Roles = user.Roles
};
return View(viewModel);
}
在我的详细信息视图中 -
@model TRS.ViewModels.RegisterViewModel
<table>
<tr>
<td>User Name</td>
<td>@Model.UserName</td>
</tr>
<tr>
<td>Email</td>
<td>@Model.Email</td>
</tr>
<tr>
<td>First Name</td>
<td>@Model.FirstName</td>
</tr>
<tr>
<td>Last Name</td>
<td>@Model.LastName</td>
</tr>
<tr>
<td>Roles</td>
<td>@foreach (Role role in Model.Roles) {
@role.RoleName<br />
}</td>
</tr>
但我只是从User模型获取日期,没有UserDetails的日期。所以我可以看到用户名,电子邮件和rolles,但不能看到名字或姓氏。
你能看到我在哪里出错吗?
由于
答案 0 :(得分:3)
删除该行
user.UserDetails = new UserDetails();
这样做,您可以创建一个新的空UserDetails
实例。
来自您的上下文的user.UserDetails
将被该空实例替换。
修改强>
可能最好避免NRE
user.UserDetails = user.UserDetails ?? new UserDetails();
答案 1 :(得分:0)
不要使用user.UserDetails = new UserDetails()它将详细信息从db更改为新的详细信息。您可以在linq请求中获取您的viewmodel:
public ViewResult Details(string id)
{
var viewmodel = context.Users
.Where(i => i.UserName == id)
.Select(user=>new RegisterViewModel
{
UserName = user.UserName,
FirstName = user.UserDetails.FirstName,
LastName = user.UserDetails.LastName,
Salary = user.UserDetails.Salary,
Email = user.Email,
Roles = user.Roles
})
.Single();
return View(viewModel);
}