[英]How to get related data from database in ASP.NET Core MVC
I am new one at that type development and I'm wondering how can I get related data.我是该类型开发的新手,我想知道如何获取相关数据。
I have 2 tables AspNetUsers
and Accounts
.我有 2 个表AspNetUsers
和Accounts
。 In Accounts
table there are only 3 columns Id
, UserId
join AspNetUsers
table, and Amount
.在Accounts
表中只有 3 列Id
、 UserId
join AspNetUsers
表和Amount
。 So, what I want to do, is just get this account information for current logged in user.所以,我想做的就是获取当前登录用户的这个帐户信息。
I was trying something that I have found in documentation, it works, but shows strange result:我正在尝试在文档中找到的东西,它可以工作,但显示出奇怪的结果:
Index.cshtml
: Index.cshtml
:
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
@using Microsoft.AspNetCore.Identity
@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager
@{
var user = await UserManager.GetUserAsync(User);
}
@if (SignInManager.IsSignedIn(User))
{
<div class="text-center">
<h1 class="display-4">Welcome back, @(user.Email.Split("@")[0])</h1>
</div>
<div>
<h5>Your balance: @Html.DisplayNameFor(model => model.account)</h5>
</div>
}
else
{
<div class="text-center">
<h1 class="mb-3">Welcome, new one here? Go on and create account!</h1>
</div>
}
Index.cshtml.cs
: Index.cshtml.cs
:
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
private readonly WebBankDbContext _context;
private readonly UserManager<IdentityUser> userManager;
private readonly SignInManager<IdentityUser> signInManager;
public IdentityUser user;
public Account account;
public IndexModel(SignInManager<IdentityUser> signInManager, UserManager<IdentityUser> userManager, ILogger<IndexModel> logger, WebBankDbContext context)
{
_logger = logger;
_context = context;
this.userManager = userManager;
this.signInManager = signInManager;
}
public async Task OnGetAsync()
{
if (signInManager.IsSignedIn(User))
{
user = await userManager.GetUserAsync(User);
account = (from st in _context.Accounts where st.UserId == user.Id select st).First();
}
}
}
I was debugging this code with breakpoints and had found, that there is correct information in account
, but on page it shows like this:我正在用断点调试这段代码,发现account
中有正确的信息,但在页面上显示如下:
Your balance: account
What's wrong?怎么了? How can I fix this?我怎样才能解决这个问题? Thanks.谢谢。
DisplayNameFor
displays name for the model (also your value is in account.Amount
, not just account
). DisplayNameFor
显示模型的名称(您的值也在account.Amount
中,而不仅仅是account
)。
Just change to:只需更改为:
<h5>Your balance: @(Model.account.Amount)</h5>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.