[EF Core]数据迁移(二)
摘要
在实际项目中,大多都需要对业务逻辑以及操作数据库的逻辑进行分成操作,这个时候该如何进行数据的迁移呢?
步骤
上篇文章:EF Core数据迁移操作
比如,我们将数据上下文放在了Data层。
看一下BlogContext内容如下:
public class BlogContext : DbContext { public BlogContext(DbContextOptions options) : base(options) { } public DbSet<User> Users { set; get; } }
在appsetting中配置连接字符串
{ "ConnectionStrings": { "DefaultConnection": "Server=localhost;database=MyBlogDb;uid=root;pwd=abcd;" }, "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } } }
在StartUp启动类中,做如下操作:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Wolfy.Blog.Data; namespace Wolfy.Blog { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) {
string connStr = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext<BlogContext>(options => options.UseMySQL(connStr, opt => opt.MigrationsAssembly("Wolfy.Blog"))); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
可以看到上面可以指定迁移程序集
// // 摘要: // Configures the assembly where migrations are maintained for this context. // // 参数: // assemblyName: // The name of the assembly. // // 返回结果: // The same builder instance so that multiple calls can be chained. public virtual TBuilder MigrationsAssembly([CanBeNullAttribute] string assemblyName);
大概意思是配置数据迁移保持的程序集。
总结
一个简单的用法,遇到了,就记录一下,希望对你有所帮助
-
博客地址:http://www.cnblogs.com/wolf-sun/
博客版权:如果文中有不妥或者错误的地方还望高手的你指出,以免误人子弟。如果觉得本文对你有所帮助不如【推荐】一下!如果你有更好的建议,不如留言一起讨论,共同进步! 再次感谢您耐心的读完本篇文章。
分类:
[Asp.Net Core]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
2015-12-19 [工具]图片等比例压缩工具
2013-12-19 [Head First设计模式]山西面馆中的设计模式——建造者模式