Ejemplo n.º 1
0
        /// <summary>
        /// 目的: 使用離線模式修改資料
        /// </summary>
        private static void Practice08()
        {
            Course course;
            using (var db = new ContosoUniversityEntities())
            {
                course = db.Course.Find(1);
                course.Credits = CreditType.Low;
            }

            //即使attach了, 但沒有修改state, EF還是不會對DB作Update
            using (var db = new ContosoUniversityEntities())
            {
                db.Course.Attach(course);

                db.SaveChanges();
                Console.WriteLine("Before attached and change state, Credits={0}", db.Course.Find(1).Credits);
            }

            using (var db = new ContosoUniversityEntities())
            {
                db.Entry(course).State = System.Data.Entity.EntityState.Modified; //=db.Course.Attach(course);
                db.SaveChanges();

                Console.WriteLine("After attached, Credits={0}", db.Course.Find(1).Credits);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 目的: 使用 db.ChangeTracker.Entities() 實作在修改資料後 SaveChanges() 時自動填入 ModifiedOn 欄位的內容
        /// </summary>
        private static void Practice07()
        {
            using (var db = new ContosoUniversityEntities())
            {
                var course = db.Course.Find(1);

                course.Credits = CreditType.Low;

                var entry = db.Entry(course);

                Console.WriteLine("Original Value=" + entry.OriginalValues.GetValue<int>("Credits"));
                Console.WriteLine("Current Value=" + entry.CurrentValues.GetValue<int>("Credits"));

                Console.WriteLine("State:" + "\t" + entry.State);

                db.SaveChanges();
            }
        }