Mysql EF Core 快速構建 Web Api

(1)首先建立一個.net core web api web項目;mysql

(2)由於咱們使用的是ef鏈接mysql數據庫,經過NuGet安裝MySql.Data.EntityFrameworkCore,以來的ef core 也會被安裝.ios

(2)在appsettings.json中添加以下數據庫鏈接字符串.web

(2)建立數據庫對應的model--AppUsersql

public class AppUser
    {
        public int Id { get; set; }

        public string CompanyName { get; set; }

        public string Name { get; set; }
    }

 

(3)建立dbcontext數據庫

public class UserContext:DbContext
    {
        public UserContext(DbContextOptions<UserContext> options) : base(options)
        {

        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<AppUser>()
                .ToTable("Users")
                .HasKey(u => u.Id);
            base.OnModelCreating(modelBuilder);

        }
        public DbSet<AppUser> Users { get; set; }
    }

 

(4)在startup.cs中配置數據庫鏈接信息。並插入一條記錄。json

 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)
        {
            services.AddDbContext<UserContext>(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 void Configure(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, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
            InitUserDatabase(app);
        }
        public void InitUserDatabase(IApplicationBuilder app)
        {
            using (var scope = app.ApplicationServices.CreateScope())
            {
                var userContext = scope.ServiceProvider.GetRequiredService<UserContext>();
                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生成數據庫並生成表.api

(6)啓動程序並想Users表插入一條記錄.app

可是會產生錯誤信息。目前尚未完美解決。ide

相關文章
相關標籤/搜索