Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design -Version 2.0.3
Add-Migration Init
Update-Database Init
Install-Package
命令安装运行基架引擎所需的工具。
Add-Migration
命令生成用于创建初始数据库架构的代码。 此架构以(Models/MovieContext.cs 文件中的)DbContext
中指定的模型为基础。 Init
参数用于为迁移命名。 可以使用任意名称,但是按照惯例应选择描述迁移的名称。 有关详细信息,请参阅迁移简介。
Update-Database
命令在用于创建数据库的 Migrations/{time-stamp}_InitialCreate.cs 文件中运行 Up
方法。
public partial class Blog
{
public Blog()
{
Post = new HashSet<Post>();
} public int BlogId { get; set; }
public string Url { get; set; } public ICollection<Post> Post { get; set; }
} public partial class Post
{
public int PostId { get; set; }
public int BlogId { get; set; }
public string Content { get; set; }
public string Title { get; set; } public Blog Blog { get; set; }
} public partial class BloggingContext : DbContext
{
public BloggingContext()
{
} public BloggingContext(DbContextOptions<BloggingContext> options)
: base(options)
{
} public virtual DbSet<Blog> Blog { get; set; }
public virtual DbSet<Post> Post { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
//warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Blogging;Trusted_Connection=True;");
}
} protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>(entity =>
{
entity.Property(e => e.Url).IsRequired();
}); modelBuilder.Entity<Post>(entity =>
{
entity.HasOne(d => d.Blog)
.WithMany(p => p.Post)
.HasForeignKey(d => d.BlogId);
});
}
}