1 2 3 | 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
方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | 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); }); } } |
分类:
Asp.Net/C#
标签:
asp.net core
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理