I am using asp.net core with Identity. For user I have this class:
public class User : IdentityUser
{
public List<Rate> Rates { get; set; }
}
I would like to get Rates inside Razor, how can this be done with the Name field (User.Identity.Name).
First, please confirm whether you have successfully added a
one to many
relation ofRate table
for Identityuser and generated the Rate table in the database.
Please change all Identityuser references (except where the User class inherits) in your project to your customized User class, including the relevant view page and the startup class.
And then change the ApplicationDbContext as follow:
public class ApplicationDbContext : IdentityDbContext<User>
{
public DbSet<Rate> Rate { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
Then excute migration command. More details, refer to this video.
Here is my Rate Class:
public class Rate
{
[Key]
public int Id { get; set; }
public int rate { get; set; }
public virtual User User { get; set; }
}
After completing the above operations, add relevant Rates data
to the database.
Then start the project, log in the user information, and then use the following code in the corresponding action and view to show Rates of associated Name field:
[Authorize]
public class AccountController : Controller
{
private readonly ApplicationDbContext _context;
public AccountController(ApplicationDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
var rates = await _context.Rate.Include(host => host.User).Where(x => x.User.UserName == User.Identity.Name).ToListAsync();
return View(rates);
}
}
Razor View:
@model IEnumerable<Rate>
@{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Index</h1>
UserName: @User.Identity.Name related Rates data:
<table class="table table-bordered">
<tr>
<th>Id</th>
<th>Rate</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@item.Id</td>
<td>@item.rate</td>
</tr>
}
</table>
Here is the test result: