ASP.NET Core學習之五 EntityFrameworkCore

  目的:運用EntityFrameworkCore ,使用codefirst開發html

1、建立web項目git

  建立一個不進行身份驗證的   ASP.NET Core Web Application (.NET Core)  項目;web

2、引用包數據庫

  引用 EntityFrameworkCore、EntityFrameworkCore.SqlServerjson

3、準備工做app

   在項目添加一個User實體測試

  public class User
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
    }

4、建立DbContextspa

 

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

        }

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

5、配置Startup.net

  首頁、在appsettings.json添加連接字符串code

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog=SmallBlog;User ID=sa;Password=123456"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

  而後、在Startup添加DbContext

 public void ConfigureServices(IServiceCollection services)
        { 
            services.AddDbContext<SbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
             
            services.AddMvc();
        }
         

6. 進行遷移

  其餘文章都是安裝 Microsoft.EntityFrameworkCore.Tools 去遷移,我本身試了其實很簡單,和之前的ef同樣

  微軟文檔:https://docs.microsoft.com/zh-cn/ef/core/get-started/aspnetcore/new-db?view=aspnetcore-2.1

 在 包管理器控制檯 下執行如下命令,沒出錯的話,數據庫就自動建好了

 PM> Add-Migration InitialCreate
 PM> Update-Database

7.測試

 var user = _userRepository.GetById(1);
            if (user == null)
            { 
                _userRepository.Add(new User()
                { 
                    Password = "111",
                    UserName = "handsome"
                });
            }

            user = _userRepository.GetById(1);

 

業餘時間很少,直接上代碼

源碼下載地址:https://gitee.com/zmsofts/XinCunShanNianDaiMa/blob/master/.netcore/SmallBlog.rar  

 

 

參考文章:

https://www.cnblogs.com/baobaodong/p/5870851.html

相關文章
相關標籤/搜索