[英]How can I create many tables in my database using EF Core migrations
I am doing a bookstore project and I first created one table for the adding book.我正在做一个书店项目,我首先为添加书籍创建了一个表。 So I want to add login and signup pages and store to the database, but I am confused about how I can add another table or create tables related to my need using migrations.因此,我想添加登录和注册页面并将其存储到数据库中,但我对如何使用迁移添加另一个表或创建与我的需求相关的表感到困惑。 I have attached my DbContext
class.我附上了我的DbContext
类。
Forgive me my English is not so good.原谅我的英语不是很好。 I am waiting for your answers.我在等你的答案。 Thanks谢谢
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CODEwithZAKI.Data
{
public class BookStoreContext : DbContext
{
public BookStoreContext(DbContextOptions<BookStoreContext> options)
: base(options)
{
}
public DbSet<Books> Books { get; set; }
}
}
For how to add a new table to the database with ef core code first, you can follow the below steps:关于如何先使用ef核心代码向数据库添加新表,可以按照以下步骤操作:
1.Create your new table as a model 1.创建您的新表作为模型
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
//other properties
}
2.Add its entry in DbContext class 2.在DbContext类中添加其条目
public class BookStoreContext : DbContext
{
public BookStoreContext(DbContextOptions<BookStoreContext> options)
: base(options)
{
}
public DbSet<Books> Books { get; set; }
public DbSet<Author> Authors { get; set; }
}
3.Create a new migration with the addition of Posts in Package Manager Console 3.在包管理器控制台中添加帖子创建一个新的迁移
Add-Migration AuthorMigration
4.Update database 4.更新数据库
Update-Database
To add new tables to you database using migrations is simply a matter of extending your BookStoreContext
with the new sets and then running the migration commands.使用迁移向数据库添加新表只需使用新集合扩展BookStoreContext
,然后运行迁移命令即可。 As an example using dotnet
command.作为使用dotnet
命令的示例。
Generate the new migration script:生成新的迁移脚本:
dotnet ef migrations add DESCRIPTION_OF_YOUR_MIGRATION
Run the migration:运行迁移:
dotnet ef database update
And that's it.就是这样。 Everytime you add new records to your BookStoreContext you just go through the above two commands to run the EF Core migration process.每次向 BookStoreContext 添加新记录时,您只需通过上述两个命令来运行 EF Core 迁移过程。
PS For login/authentication/identity it is recommended to utilize ASP.NET Core Identity . PS 对于登录/身份验证/身份,建议使用ASP.NET Core Identity 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.