探索Aspnetcore+mysql+efcore

來源:互聯網
上載者:User

標籤:time   route   task   err   end   startup   mic   under   dev   

摘要

之前嘗試了,建立asp.net core網站,那麼如何和mysql建立串連,如果操作mysql?本篇將嘗試使用EntityFrameworkCore進行mysql的操作。

一個例子

首先建立一個空的Asp.net core網站,

安裝MySql.Data.EntityFrameworkCore

http://www.nuget.org/packages/MySql.Data.EntityFrameworkCore/7.0.5-IR21

安裝成功

這時你可以在project.json中看到MySql.Data.EntityFrameworkCore依賴的配置

建立一個User類

    public class User    {        public int Id { set; get; }        public string Name { set; get; }        public DateTime Dt { set; get; } = DateTime.Now;    }

這裡使用 db first方式進行資料庫的操作,添加一個test的資料庫,然後建立一個user表

添加資料庫上下文類。

using Microsoft.EntityFrameworkCore;using MySQL.Data.EntityFrameworkCore.Extensions;using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Wolfy.EfMySql.Models;namespace Wolfy.EfMySql.Data{    public class TestContext : DbContext    {        public DbSet<User> User { set; get; }        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)            => optionsBuilder.UseMySQL(@"Server=localhost;database=test;uid=root;pwd=123456");    }}

添加控制器

using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Mvc;using Wolfy.EfMySql.Data;using Wolfy.EfMySql.Models;// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860namespace Wolfy.EfMySql.Controllers{    public class HomeController : Controller    {        // GET: /<controller>/        public IActionResult Index()        {            var db = new TestContext();            db.Add(new User { Name = "Hello world" });            db.SaveChanges();            var lst = db.Set<User>().ToList();            return View(lst);        }    }}

添加路由

using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Http;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;namespace Wolfy.EfMySql{    public class Startup    {        // This method gets called by the runtime. Use this method to add services to the container.        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940        public void ConfigureServices(IServiceCollection services)        {                    }        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)        {            loggerFactory.AddConsole();            if (env.IsDevelopment())            {                app.UseDeveloperExceptionPage();            }            app.UseMvc(routes =>            {                routes.MapRoute(name: "default", template: "{controller=Home}/{action=index}");            });        }    }}

瀏覽Index

通過上面,可以看出,是沒有添加mvc服務,引起的,修改如下:

        public void ConfigureServices(IServiceCollection services)        {            services.AddMvc();        }

視圖

@*    For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860*@@model List<Wolfy.EfMySql.Models.User><ul style="list-style-type:none;">    @foreach (var item in Model)    {        <li>@item.Id   @item.Name   @item.Dt.ToString("yyyy-MM-dd HH:mm:ss")</li>    }</ul>

重新整理頁面

結語

這裡算是嘗嘗鮮。關於asp.net core的更多內容,需要參考https://www.asp.net/core

探索Aspnetcore+mysql+efcore

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.