EFCore自己用的點東西
測試一下EF core 的操作 蛀牙總是用導航屬性有的時候有點不理解 寫個例子給自己用
class Program { static void Main(string[] args) { MyDbContext myDbContext = new MyDbContext(); try { #region 添加業務/第一種添加 student中把導航屬性school也加進去 這是新的用法 //AddWithDaoHangShuXing(myDbContext); #endregion #region 添加業務/第二種添加 先添加student 添加後再添加school //AddWithSingle(myDbContext); #endregion #region 修改業務 按照通俗的業務邏輯 那麼修改傳回來的就是類型本身 即所有的屬性都可以更改 //1.首先 查出來所有的學生數據 //1.1 lambada表達式 var students = myDbContext.Student.ToList(); var studentWithDaoHangShuXings = myDbContext.Student.Include(x => x.School).ToList(); var studentWithDaoHangShuXingProvinceces = myDbContext.Student.Include(x => x.School).ThenInclude(x=>x.Province).ToList(); //1.2 linq var studentLinqs = (from s in myDbContext.Student select new { s.StudentId, s.StudentAge, s.StudentName, s.School }).ToList(); #endregion Console.WriteLine("操作完畢!"); } catch (Exception ex) { } Console.ReadLine(); } private static void AddWithSingle(MyDbContext myDbContext) { Student student = new Student { StudentName = "張汶萊", StudentAge = 26 }; myDbContext.Student.Add(student); myDbContext.SaveChanges(); School school = new School { StudentId = student.StudentId, SchAddress = "廣發學校", SchName = "廣發學校地址" }; myDbContext.School.Add(school); myDbContext.SaveChanges(); } private static void AddWithDaoHangShuXing(MyDbContext myDbContext) { Province province = new Province { ProvinceLeaderName = "黨中央", ProvinceName = "陝西省" }; School school = new School { SchAddress = "老毛學校地址", SchName = "老毛小學", SchoolId = 0, Province = province }; Student student = new Student { StudentAge = 12, StudentName = "梁非凡", School = school, StudentId = 0 }; myDbContext.Student.Add(student); myDbContext.SaveChanges(); } } public class Province { public int ProvinceId { get; set; } public string ProvinceName { get; set; } public string ProvinceLeaderName { get; set; } } public class School { public int SchoolId { get; set; } public int StudentId { get; set; } public string SchAddress { get; set; } public string SchName { get; set; } public Province Province { get; set; } } public class MyDbContext : DbContext { /// <summary> /// 配置數據連接資訊 /// </summary> /// <param name="optionsBuilder"></param> protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Server=.;DataBase=TestMyDb;Uid=sa;Pwd=123456"); base.OnConfiguring(optionsBuilder); } public DbSet<Student> Student { get; set; } public DbSet<School> School { get; set; } } public class Student { public int StudentId { get; set; } public string StudentName { get; set; } public int StudentAge { get; set; } //導航屬性 public School School { get; set; } }