要完成这些步骤,您需要 Visual Studio 2022。
基于当前文档:
public class OrderDetail
{
public int OrderDetailID { get; set; }
public int OrderID { get; set; }
public int ProductID { get; set; }
public int Quantity { get; set; }
public Order Order { get; set; }
}
public class Order
{
public int OrderID { get; set; }
public int CustomerID { get; set; }
public int EmployeeID { get; set; }
public DateTime OrderDate { get; set; }
public List<OrderDetail> OrderDetails { get; set; }
}
这是一个非常简单的模型,只包含两个类,Order 和 OrderDetail 具有一对多的关系。下一步是添加一个新的上下文类并确保继承自 DbContext 类
public class MyContext : DbContext
{
public DbSet<OrderDetail> OrderDetails { get; set; }
public DbSet<Order> Orders { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Data Source=(localdb)\ProjectsV13;Initial Catalog=StoreDB;");
}
}
现在要使用模型中的迁移创建数据库,请安装以下软件包;
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.Design
安装这些包后,在包管理器控制台中运行以下命令。
Add-Migration Initial
此命令构建迁移以为您的模型创建初始表集。执行成功后,再运行以下命令。
Update-Database to apply the new migration to the database. This command creates the database before applying migrations.
如果您需要学习如何建立关系,以下网站有非常好的文档和实体框架演练。
希望以下链接对您有所帮助:
https://entityframeworkcore.com
https://www.learnentityframeworkcore.com