简体   繁体   中英

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 . In Accounts table there are only 3 columns Id , UserId join AspNetUsers table, and 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 :

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

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:

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 ).

Just change to:

<h5>Your balance: @(Model.account.Amount)</h5>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM