ef core mysql 创建数据库_Mysql EF Core 快速构建 Web Api

(1)首先创建一个.net core web api web项目;

(2)因为我们使用的是ef连接mysql数据库,通过NuGet安装MySql.Data.EntityFrameworkCore,以来的ef core 也会被安装.

(2)在appsettings.json中添加如下数据库连接字符串.

80e75d207c93c4536f256faedea18ad5.png

(2)创建数据库对应的model--AppUser

public classAppUser

{public int Id { get; set; }public string CompanyName { get; set; }public string Name { get; set; }

}

(3)创建dbcontext

public classUserContext:DbContext

{public UserContext(DbContextOptions options) : base(options)

{

}protected override voidOnModelCreating(ModelBuilder modelBuilder)

{

modelBuilder.Entity()

.ToTable("Users")

.HasKey(u=>u.Id);base.OnModelCreating(modelBuilder);

}public DbSet Users { get; set; }

}

(4)在startup.cs中配置数据库连接信息。并插入一条记录。

public IConfiguration Configuration { get; }//This method gets called by the runtime. Use this method to add services to the container.

public voidConfigureServices(IServiceCollection services)

{

services.AddDbContext(options =>{

options.UseMySQL(Configuration.GetConnectionString("MysqlUser"));

});

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

}//This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

public voidConfigure(IApplicationBuilder app, IHostingEnvironment env)

{if(env.IsDevelopment())

{

app.UseDeveloperExceptionPage();

}else{//The default HSTS value is 30 days. You may want to change this for production scenarios, seehttps://aka.ms/aspnetcore-hsts.

app.UseHsts();

}

app.UseHttpsRedirection();

app.UseMvc();

InitUserDatabase(app);

}public voidInitUserDatabase(IApplicationBuilder app)

{using (var scope =app.ApplicationServices.CreateScope())

{var userContext = scope.ServiceProvider.GetRequiredService();if (!userContext.Users.Any())

{

userContext.Users.Add(new Models.AppUser { Name = "daniel cui", CompanyName = "bat company"});

userContext.SaveChanges();

}

}

}

(5)执行Add-Migration init生成Migrations文件夹,执行Update-Database init生成数据库并生成表.

(6)启动程序并想Users表插入一条记录.

但是会产生错误信息。目前还没有完美解决。

324615b102551f1ff24cd6873d9336c7.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值