如何使用 EF 核心添加新表

ane*_*ko5 7 database entity-framework-core asp.net-core

当我将 Identity 添加到项目时,我已经创建了一个现有的数据库。现在我想向数据库添加更多表,但不知道如何。

我为它创建了一个模型:

public class Match
{
    public Guid ID { get; set; }
    public string HomeTeam { get; set; }
    public string AwayTeam { get; set; }
    public int FullTimeScore { get; set; }
    public DateTime MatchStart { get; set; }  
    public int PrizePool { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的背景:

public class DynamicBettingUserContext : IdentityDbContext<IdentityUser>
{
    public DynamicBettingUserContext(DbContextOptions<DynamicBettingUserContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
    }
}
Run Code Online (Sandbox Code Playgroud)

下一步是什么?

viv*_*una 8

您需要Match在您的DynamicBettingUserContext班级中添加表格,如下所示。然后您需要Add-Migration <YourMigrationName>在包管理器控制台中添加迁移,最后,您必须Update-Database在 PMC 中运行命令。

public virtual DbSet<Match> Match { get; set; } 
Run Code Online (Sandbox Code Playgroud)

  • @aneko5 另外,如果您需要设置特定的表名称或模式名称,您可以将 `Table` 属性添加到您的类中,例如 `[Table("table_name", Schema = "schema_name")]` (2认同)
  • 如果数据库中有其他表而我们只想添加一个新表怎么办?在这种情况下,通过运行“Update-Database”,它将显示有关其他现有表的错误。 (2认同)