title: How can I create an Entity, add it to my database context, and return its attributes from another Controller?
body: <p>I'm pretty new to asp.net and c# and I recently ran into this problem which I can't seem to work around.
  Basically, I inherited the IdentityUser class like so, and added my own attributes:</p>
  <pre><code>public class ApplicationUser : IdentityUser
  {
      [ForeignKey(&quot;Wallet&quot;)]
      public int WalletID { get; set; }
      [ForeignKey(&quot;Portfolio&quot;)]
      public int PortfolioID { get; set; }
      public virtual Wallet Wallet { get; set; }
      public virtual Portfolio Portfolio { get; set; }
  }
  </code></pre>
  <p>Now, the problem occurs when I try to register using the auto generated register page because the fields <code>WalletID</code> and <code>PorfolioID</code> are
  not initialized. A few things I tried  inside the <code>Register.cshtml.cs</code> code for the Identity Account were:</p>
  <ul>
  <li>Creating a new Wallet and Portfolio using :
  <code>Wallet w = new Wallet(); Portfolio p = new Portfolio();</code>
  and assigning their id to corresponding attributes inside the <code>ApplicationUser</code>. The problem with this is that I don't know how to get the instance of the database context so they are not added to the database and therefore violate the ForeignKey constraint.</li>
  <li>Tried to get instance of  <code>WalletController</code> and <code>PortfolioController</code>, then call the <code>Create()</code> methods  from inside the <code>Register.cshtml.cs</code>, but to no avail. I also read that this is bad practice and should be avoided.</li>
  </ul>
  <p>Essentially, what I want to do is, when someone registers, create an instance of <code>Portfolio</code> and <code>Wallet</code>, add them to my database, assign their IDs to corresponding attributes inside the <code>ApplicationUser</code> and proceed with the registraton.</p>
  <p>What is the best way to solve this?</p>
  <p>The auto-generated Register.cshtml.cs:</p>
  <pre><code>using...
      namespace CryptoSimulation.Areas.Identity.Pages.Account
      {
          [AllowAnonymous]
          public class RegisterModel : PageModel
          {
              private readonly SignInManager&lt;ApplicationUser&gt; _signInManager;
              private readonly UserManager&lt;ApplicationUser&gt; _userManager;
              private readonly ILogger&lt;RegisterModel&gt; _logger;
              private readonly IEmailSender _emailSender;
      
      
              public RegisterModel(
                  UserManager&lt;ApplicationUser&gt; userManager,
                  SignInManager&lt;ApplicationUser&gt; signInManager,
                  ILogger&lt;RegisterModel&gt; logger,
                  IEmailSender emailSender)
              {
                  _userManager = userManager;
                  _signInManager = signInManager;
                  _logger = logger;
                  _emailSender = emailSender;
              }
      
              [BindProperty]
              public InputModel Input { get; set; }
      
              public string ReturnUrl { get; set; }
      
              public IList&lt;AuthenticationScheme&gt; ExternalLogins { get; set; }
      
              public class InputModel
              {
                  [Required]
                  [EmailAddress]
                  [Display(Name = &quot;Email&quot;)]
                  public string Email { get; set; }
      
                  [Required]
                  [StringLength(100, ErrorMessage = &quot;The {0} must be at least {2} and at max {1} characters long.&quot;, MinimumLength = 6)]
                  [DataType(DataType.Password)]
                  [Display(Name = &quot;Password&quot;)]
                  public string Password { get; set; }
      
                  [DataType(DataType.Password)]
                  [Display(Name = &quot;Confirm password&quot;)]
                  [Compare(&quot;Password&quot;, ErrorMessage = &quot;The password and confirmation password do not match.&quot;)]
                  public string ConfirmPassword { get; set; }
              }
      
              public async Task OnGetAsync(string returnUrl = null)
              {
                  ReturnUrl = returnUrl;
                  ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
              }
      
              public async Task&lt;IActionResult&gt; OnPostAsync(string returnUrl = null)
              {
                  returnUrl ??= Url.Content(&quot;~/&quot;);
                  ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
                  if (ModelState.IsValid)
                  {
                       
                      
                      var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email };
                      var result = await _userManager.CreateAsync(user, Input.Password);
                      if (result.Succeeded)
                      {
                          _logger.LogInformation(&quot;User created a new account with password.&quot;);
      
                          var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                          code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                          var callbackUrl = Url.Page(
                              &quot;/Account/ConfirmEmail&quot;,
                              pageHandler: null,
                              values: new { area = &quot;Identity&quot;, userId = user.Id, code = code, returnUrl = returnUrl },
                              protocol: Request.Scheme);
      
                          await _emailSender.SendEmailAsync(Input.Email, &quot;Confirm your email&quot;,
                              $&quot;Please confirm your account by &lt;a href='{HtmlEncoder.Default.Encode(callbackUrl)}'&gt;clicking here&lt;/a&gt;.&quot;);
      
                          if (_userManager.Options.SignIn.RequireConfirmedAccount)
                          {
                              return RedirectToPage(&quot;RegisterConfirmation&quot;, new { email = Input.Email, returnUrl = returnUrl });
                          }
                          else
                          {
                              await _signInManager.SignInAsync(user, isPersistent: false);
                              return LocalRedirect(returnUrl);
                          }
                      }
                      foreach (var error in result.Errors)
                      {
                          ModelState.AddModelError(string.Empty, error.Description);
                      }
                  }
      
                  // If we got this far, something failed, redisplay form
                  return Page();
              }
          }
      }
  </code></pre>
  <p>The auto-generated WalletController (PortfolioController is pretty much the same):</p>
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Threading.Tasks;
  using Microsoft.AspNetCore.Mvc;
  using Microsoft.AspNetCore.Mvc.Rendering;
  using Microsoft.EntityFrameworkCore;
  using CryptoSimulation.Data;
  using CryptoSimulation.Models;
  
  namespace CryptoSimulation.Controllers
  {
      public class PortfolioController : Controller
      {
          private readonly ApplicationDbContext _context;
  
          public PortfolioController(ApplicationDbContext context)
          {
              _context = context;
          }
  
          // GET: Portfolio
          public async Task&lt;IActionResult&gt; Index()
          {
              return View(await _context.Portfolio.ToListAsync());
          }
  
          // GET: Portfolio/Details/5
          public async Task&lt;IActionResult&gt; Details(int? id)
          {
              if (id == null)
              {
                  return NotFound();
              }
  
              var portfolio = await _context.Portfolio
                  .FirstOrDefaultAsync(m =&gt; m.PortfolioID == id);
              if (portfolio == null)
              {
                  return NotFound();
              }
  
              return View(portfolio);
          }
  
          // GET: Portfolio/Create
          public IActionResult Create()
          {
              return View();
          }
  
          // POST: Portfolio/Create
          // To protect from overposting attacks, enable the specific properties you want to bind to.
          // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
          [HttpPost]
          [ValidateAntiForgeryToken]
          public async Task&lt;IActionResult&gt; Create([Bind(&quot;PortfolioID&quot;)] Portfolio portfolio)
          {
              if (ModelState.IsValid)
              {
                  _context.Add(portfolio);
                  await _context.SaveChangesAsync();
                  return RedirectToAction(nameof(Index));
              }
              return View(portfolio);
          }
  
  
  
          // GET: Portfolio/Edit/5
          public async Task&lt;IActionResult&gt; Edit(int? id)
          {
              if (id == null)
              {
                  return NotFound();
              }
  
              var portfolio = await _context.Portfolio.FindAsync(id);
              if (portfolio == null)
              {
                  return NotFound();
              }
              return View(portfolio);
          }
  
          // POST: Portfolio/Edit/5
          // To protect from overposting attacks, enable the specific properties you want to bind to.
          // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
          [HttpPost]
          [ValidateAntiForgeryToken]
          public async Task&lt;IActionResult&gt; Edit(int id, [Bind(&quot;PortfolioID&quot;)] Portfolio portfolio)
          {
              if (id != portfolio.PortfolioID)
              {
                  return NotFound();
              }
  
              if (ModelState.IsValid)
              {
                  try
                  {
                      _context.Update(portfolio);
                      await _context.SaveChangesAsync();
                  }
                  catch (DbUpdateConcurrencyException)
                  {
                      if (!PortfolioExists(portfolio.PortfolioID))
                      {
                          return NotFound();
                      }
                      else
                      {
                          throw;
                      }
                  }
                  return RedirectToAction(nameof(Index));
              }
              return View(portfolio);
          }
  
          // GET: Portfolio/Delete/5
          public async Task&lt;IActionResult&gt; Delete(int? id)
          {
              if (id == null)
              {
                  return NotFound();
              }
  
              var portfolio = await _context.Portfolio
                  .FirstOrDefaultAsync(m =&gt; m.PortfolioID == id);
              if (portfolio == null)
              {
                  return NotFound();
              }
  
              return View(portfolio);
          }
  
          // POST: Portfolio/Delete/5
          [HttpPost, ActionName(&quot;Delete&quot;)]
          [ValidateAntiForgeryToken]
          public async Task&lt;IActionResult&gt; DeleteConfirmed(int id)
          {
              var portfolio = await _context.Portfolio.FindAsync(id);
              _context.Portfolio.Remove(portfolio);
              await _context.SaveChangesAsync();
              return RedirectToAction(nameof(Index));
          }
  
          private bool PortfolioExists(int id)
          {
              return _context.Portfolio.Any(e =&gt; e.PortfolioID == id);
          }
      }
  }
  </code></pre>