Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Database Table from Model in .NET Core

Just started learning .NET Core. I have managed to move Migration folder, ApplicationDbContext and ApplicationUser file to .net core class library project and referenced it to web project. This is working fine as I can see default 7 tables related user roles and claims in my database.

Now I have model something like

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Domain.Model
{
   [Table("Employee")]
   public class Employee
   {
     [Key]
     public int EmployeeId{get; set;}

     [Required, MaxLength(100)]
     public string Name {get;set;}
   }
}

In ApplicationDbContext file

namespace BLL
{
   public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole<int>, int>
  {
      public DbSet<Employee> Employees {get;set;}

      public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options): base(options)
      {

      }

      protected override void OnModelCreating(ModelBuilder builder)
      {
        base.OnModelCreating(builder);            
      }
  }
}

Then I created controller class EmployeeController and in Index method just created new object of Employee as

public class EmployeeController : Controller
{
    public IActionResult Index()
    {
        Employee e = new Employee();
        return View();
    }
}

with Index view then I run a project but this didn't create Employee table in my database.

I have refereed these articles

to change aspnet user tables primary key data types

https://medium.com/@goodealsnow/asp-net-core-identity-3-0-6018fc151b4#.fxdzevyzn

CRUD operation in .NET Core

https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model

I am getting error while adding controller with views, using Entity Framework and thus I had to create empty controller.EmployeeController ControllAddingError

How should I create inject my model(s) to ApplicationDbContext or generate migration file to update database?

like image 971
Bhuban Shrestha Avatar asked Oct 29 '22 13:10

Bhuban Shrestha


1 Answers

in the package manager console:

Add-Migration init

then:

Update-Database
like image 194
Beaumind Avatar answered Nov 02 '22 11:11

Beaumind