ASP.NET Core2.0項目實戰-007

DbContext對象

 

有兩種 

一個是Code First

還有就是DataBase First

using KevinTest001.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace KevinTest001.Controllers
{
    public class EFController:Controller
    {
        private MyDbContext _myDbContext;

        public EFController(MyDbContext myDbContext)
        {
            this._myDbContext = myDbContext;
        }



        //創建一個委託像一個函數,方法,不過沒有具體的
        //delegate
        //o=>o.Name=="張三"  一種委託的寫法
        //LINQ 和SQL轉換,差不多

        public IActionResult Index()
        {
            // var i = 1;
            var a = new { A = "張三" };   //匿名對象

            ////添加一個對象
            //_myDbContext.Persons.Add(new Person()
            //    {
            //    Name="張三",
            //   Sex="男"
 
            //});

            //_myDbContext.Persons.Add(new Person()
            //{
            //    Name = "張三1",
            //    Sex = "男"

            //});
            ////
            //int i= _myDbContext.SaveChanges();


            //刪除
           // _myDbContext.Persons.Remove(_myDbContext.Persons.Find(1));   //找到1的這條


            var item = _myDbContext.Persons.Find(2);
            item.Name = "李四";     //改值
            int j = _myDbContext.SaveChanges();


            //var list= _myDbContext.Persons.ToList();
            var list = _myDbContext.Persons.Where(o=>o.Name=="李四").ToList();   //_myDbContext.Persons.各種where.ToList();
           // var list = _myDbContext.Persons.Where(o => o.Name == "李四").FirstOrDefault();   //第一個 對象
            // return View();
            return Content("a");
        }

    }
}
//{
//  "Logging": {
//    "LogLevel": {
//      "Default": "Warning"
//    }
//  },
//  "AllowedHosts": "*"
//}
{

  "ConnectionStrings": {
    //"DefaultConnection": "Server=(Lovaldb)\\SQLEXPRESS;Database=ILPF ;Trusted_Connection=True;MultipleActiveResultSets=true"
    "DefaultConnection": "data source =192.168.XX.XX;initial catalog=ILPF ;user id =sa;password=xXXX;"
    //本地用.
  },

  "name": "Kevin",


  "person0": {
    "age": 20,
    "name": "Tom"
  },



  "person1": [
    {
      "age": 20,
      "name": "Tom"
    },
    {
      "age": 20,
      "name": "Tom"
    }
  ],

  "person2": [
    {
      "age": [
        { "abc": 20 }
      ],
      "name": "Tom"
    },
    {
      "age": 20,
      "name": "Tom"
    }
  ],

  "person": {
    "name": "John",
    "age":20

  }


}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章