首页 文章

从.NET Core中的模型创建数据库表

提问于
浏览
3

刚开始学习.NET Core . 我已设法将 Migration folderApplicationDbContextApplicationUser 文件移动到.net核心类库项目并将其引用到Web项目 . 这工作正常,因为我可以在我的数据库中看到默认的7个表相关的用户角色和声明 .

现在我有类似的模型

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;}
   }
}

在ApplicationDbContext文件中

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);            
      }
  }
}

然后我创建了控制器类 EmployeeController 并在Index方法中刚创建了Employee的新对象as

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

使用Index视图然后我运行一个项目,但这并没有在我的数据库中创建Employee表 .

我已经对这些文章进行了评论

更改aspnet用户表主键数据类型

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

.NET Core中的CRUD操作

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

我在添加 controller with views, using Entity Framework 时遇到错误,因此我不得不创建空控制器 .
EmployeeController

ControllAddingError

我应该如何创建将模型注入ApplicationDbContext或生成迁移文件以更新数据库?

1 回答

  • 3

    在包管理器控制台中:

    Add-Migration init
    

    然后:

    Update-Database
    

相关问题