Search code examples
c#entity-frameworkasp.net-coreef-code-firstlocaldb

ASP.NET Core Web Application: create model class that has default User model as property


I have created a new project using the template for "ASP.NET Core 3.0 Web Application (Model View Controller)". It comes with authentication (register, login, logout, etc).

I now want to create a model class called InsurancePolicy that has the User property (or UserId property), obviously referencing a user in the default AspNetUsers table in my localdb.

So EFCore is code first for modelling I understand, so I have created that InsurancePolicy model class, with all the properties like Description etc. I'm following this guideline by Microsoft.

However I don't have a model class for the AspNetUsers table in the localdb, for me to create a property on Insurance policy, e.g. public AspNetUsers User {get; set;}

How do I do this? Or is there a better way to do this?

I'm new to Core so code first design as opposed to db first is still blurry for me.

UPDATE

Looks like the model for AspNetUsers table is IdentityUser. Is this true, or am I still lost?


Solution

  • For example , i will add model Book and add a foreign key to Identity user , a book belongs to one user :

    1. Create Book.cs :

      public class Book
      {
          public int Id { get; set; }
          public string Name { get; set; }
      
          public string UserId { get; set; }
          public IdentityUser User { get; set; }
      }
      
    2. Modify ApplicationDbContext to include the DbSet:

      public class ApplicationDbContext : IdentityDbContext
      {
          public DbSet<Book> Books { get; set; }
          public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
              : base(options)
          {
          }
      }
      
    3. add-migration Name and update-database to create table and relationship in database .

    4. If you want to add a book which belongs to current user in controller , you can firstly inject the services :

      private readonly ILogger<HomeController> _logger;
      private readonly ApplicationDbContext _context;
      private readonly UserManager<IdentityUser> _userManager;
      public HomeController(ILogger<HomeController> logger, ApplicationDbContext context, UserManager<IdentityUser> userManager)
      {
          _logger = logger;
          _context = context;
          _userManager = userManager;
      }
      
    5. Create book and save to database:

      Book book = new Book();
      //or search user by FindByIdAsync or FindByEmailAsync
      var user = await _userManager.GetUserAsync(HttpContext.User);
      book.User = user;
      _context.Books.Add(book);
      await _context.SaveChangesAsync();
      
    6. If you want to read book with User properties , you can try :

      using Microsoft.EntityFrameworkCore;
      
      var result= _context.Books.Include(rt => rt.User).Where(x => x.Id == 1).FirstOrDefault();