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

标签 c# asp.net asp.net-mvc asp.net-core asp.net-core-mvc

刚开始学习 .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);            
      }
  }
}

然后我创建了 Controller 类 EmployeeController 并在 Index 方法中创建了新的 Employee 对象作为

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

然后我使用索引 View 运行一个项目,但这并没有在我的数据库中创建 Employee 表。

我已经引用了这些文章

改变aspnet用户表的主键数据类型

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

.NET Core 中的 CRUD 操作

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

我在使用 Entity Framework 添加带有 View 的 controller 时出错,因此我不得不创建空 Controller 。 EmployeeController ControllAddingError

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

最佳答案

在包管理器控制台中:

Add-Migration init

然后:

Update-Database

关于c# - 从 .NET Core 中的模型创建数据库表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41900981/

相关文章:

c# - C# 是否优化了字符串文字的连接?

c# - Linq 过滤器集合内部集合

c# - ASP.NET:何时以及如何在代码后面动态更改 Gridview header 文本?

asp.net-mvc - 订阅 ServiceBus 以获取通知

JavaScript:单击复选框启用文本框

c# - "Recasting"接口(interface)的子类实例(声明为基类) - 为什么它有效?

c# - 在 C# 中循环遍历字母表以输出到 Excel 的最佳方法是什么?

c# - ASP.NET 表达式生成器什么时候最有用?

sql - Entity Framework Lambda 表达式中的交叉连接

c# - ASP MVC 5 和 Bootstrap 中表单控件的对齐不正确