---
# System prepended metadata

title: .net core 6 練習
tags: [tutorials]

---

---
title: .net core 6 練習
tags: tutorials
disqus: hackmd
---
<style>

.text-center{
    text-align: center; //文字置中
}
.text-left{
    text-align: left; //文字靠左
}
.text-right{
    text-align: right; //文字靠右
}
.red{
    color: red; //文字靠右
}

</style>

#  .net core 6 + EF core



0.下載範例專案(拿到裡面的.mdf檔 local資料庫)
https://drive.google.com/drive/folders/13rJcr5bLrOOP1vEEvYC-y1s4NKehf3bi?usp=sharing

1.打開vs 建立一個core 6 專案

2.neget 安裝
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools

3.vs 檢視>其他視窗>套件管理器主控台

PM>

Scaffold-DbContext "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=<span class="red">D:\jenni\Desktop\Todo\Todo.mdf</span>;Integrated Security=True;Connect Timeout=30" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Force -CoNtext TodoContext

*紅字要改成你放mdf檔的位置

4.appsetting.json寫(紅字可改)

 "ConnectionStrings": {
    "<span class="red">TodoDatabase</span>": "Server=(LocalDB)\\MSSQLLocalDB;Database=<span class="red">D:\\jenni\\Desktop\\Todo\\Todo.mdf</span>;Integrated Security=True;Connect Timeout=30"
  }

5.在Program.cs補程式碼去讀appsetting.json的資料
     
     var connectString = builder.Configuration.GetConnectionString("TodoDatabase");

6.在Program.cs補程式碼加入DbContext

     builder.Services.AddDbContext<TodoContext>(x => x.UseSqlServer(connectString));
    
7.在Controller Class裡補欄位和建構子

        //欄位
        private readonly TodoContext _todoContext;

        //建構子
        public TodoController(TodoContext todoContext)
        {
        _todoContext = todoContext;
        }
    
8.在Controller 裡寫一個Get跑起來試試看
    
    
    
        [HttpGet]
        public IEnumerable<TodoList> Get()
        {
            return _todoContext.TodoLists.ToList();
        }
        




###### tags: `tutorial`
