Example #1
0
        /*
         * the DbContext is not aware of disconnected entities
         * because entities were added or modified out of the scope of the current DbContext instance.
         * So, you need to attach the disconnected entities to a context with appropriate EntityState
         * in order to perform CUD (Create, Update, Delete) operations to the database.
         */
        public static void AddUpdateEntityInDisconnectedScenario()
        {
            Console.WriteLine("*** AddUpdateEntityInDisconnectedScenario Starts ***");

            // disconnected entities
            var newStudent = new Student()
            {
                StudentName = "Bill"
            };
            var existingStudent = new Student()
            {
                StudentID = 10, StudentName = "Chris"
            };

            using (var context = new SchoolDBEntities())
            {
                //Log DB commands to console
                context.Database.Log = Console.WriteLine;

                context.Entry(newStudent).State      = newStudent.StudentID == 0 ? EntityState.Added : EntityState.Modified;
                context.Entry(existingStudent).State = existingStudent.StudentID == 0 ? EntityState.Added : EntityState.Modified;

                context.SaveChanges(); // Executes Delete command
            }

            Console.WriteLine("*** AddUpdateEntityInDisconnectedScenario Ends ***");
        }
Example #2
0
        /*
         * FYI,
         *
         * ref: https://blogs.msdn.microsoft.com/marcelolr/2010/07/16/optimistic-and-pessimistic-concurrency-a-simple-explanation/
         */
        public static void OptimisticConcurrency()
        {
            Console.WriteLine("*** OptimisticConcurrency Starts ***");

            Student student = null;

            using (var context = new SchoolDBEntities())
            {
                student = context.Students.First();
            }

            //Edit student name
            student.StudentName = "Robin";

            using (var context = new SchoolDBEntities())
            {
                context.Database.Log = Console.Write;

                try
                {
                    context.Entry(student).State = EntityState.Modified;
                    context.SaveChanges();

                    Console.WriteLine("Student saved successfully.");
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    Console.WriteLine("Concurrency Exception Occurred.");
                }
            }

            Console.WriteLine("*** OptimisticConcurrency Ends ***");
        }
Example #3
0
 private static void AddStudents(string[] studentNames)
 {
     using (var context = new SchoolDBEntities())
     {
         foreach (var member in studentNames)
         {
             var newStudent = context.Students.Add(
                 new Student()
             {
                 StudentName = member
             }
                 );
             context.SaveChanges(); // Executes Insert command
         }
     }
 }
Example #4
0
        public static void SpatialDataType()
        {
            Console.WriteLine("*** SpatialDataType Starts ***");

            using (var context = new SchoolDBEntities())
            {
                context.Database.Log = Console.Write;
                //Add Location using System.Data.Entity.Spatial.DbGeography
                context.Courses.Add(new Course()
                {
                    CourseName = "New Course from SpatialDataTypeDemo", Location = DbGeography.FromText("POINT(-122.360 47.656)")
                });

                context.SaveChanges();
            }

            Console.WriteLine("*** SpatialDataTypeDemo Ends ***");
        }
Example #5
0
        static void Main(string[] args)
        {
            using (var context = new SchoolDBEntities())
            {
                var studentList = context.Students.ToList <Student>();

                //Perform create operation
                //context.Students.Add(new Student() { StudentName = "New Student" });

                //Perform Update operation
                //Student studentToUpdate = studentList.Where(s => s.StudentName == "New Student").FirstOrDefault<Student>();
                //studentToUpdate.StudentName = "Edited student1";

                ////Perform delete operation
                context.Students.Remove(studentList.ElementAt <Student>(0));

                //Execute Inser, Update & Delete queries in the database
                context.SaveChanges();
            }
        }
Example #6
0
        static void Main(string[] args)
        {
            using (var context = new SchoolDBEntities())
            {
                // Insert
                //var std = new Student()
                //{
                //    StudentName = "Jagadish"
                //};

                // Update
                //var std = context.Students.Where(x => x.StudentID.Equals(14)).FirstOrDefault();
                //std.StudentName = "Vijay";

                // Delete
                //var std = context.Students.Where(x => x.StudentID.Equals(15)).FirstOrDefault();
                //context.Students.Remove(std);

                int statuscount = context.SaveChanges();

                if (statuscount > 0)
                {
                    Console.WriteLine("Record Updated Successfully");
                }
                else
                {
                    Console.WriteLine("Insert Record Failed");
                }

                // Fetch data from the database
                //Querying with LINQ to Entities

                //var query = context.Students
                //                   .Where(s => s.StudentName == "Bill")
                //                   .FirstOrDefault<Student>();


                //Console.WriteLine(query.StudentID + query.StudentName );

                ////Querying with Object Services and Entity SQL
                //string sqlString = "SELECT VALUE st FROM SchoolDBEntities.Students " +
                //                    "AS st WHERE st.StudentName == 'Bill'";

                //var objctx = (context as IObjectContextAdapter).ObjectContext;

                //ObjectQuery<Student> student = objctx.CreateQuery<Student>(sqlString);
                //Student newStudent = student.First<Student>();

                //var anonymousResult = from s in context.Students
                //                      where s.StandardId == 1
                //                      select new
                //                      {
                //                          ID = s.StandardId,
                //                          Name = s.StudentName
                //                      };



                //foreach(var obj in anonymousResult)
                //{
                //    Console.WriteLine("ID: " + obj.ID + " Name: " + obj.Name);
                //}

                //var MethodSyntax = context.Students
                //                            .Where(x => x.StandardId == 1)
                //                            .Select(x =>
                //                            new
                //                            {
                //                                StudentID = x.StudentID,
                //                                StudentName = x.StudentName
                //                            });

                //foreach (var obj in MethodSyntax)
                //{
                //    Console.WriteLine("StudentID: " + obj.StudentID + " StudentName: " + obj.StudentName);
                //}

                //var stud1 = (from s in context.Students.Include("Standard")
                //             where s.StudentName == "Bill"
                //             select s).FirstOrDefault<Student>();


                //Console.WriteLine("ID: " + stud1.StudentID + " Name: " + stud1.StudentName + " "+ stud1.Standard.Description);

                //// disconnected new entity
                //var studentNew = new Student() { StudentName = "Bill", StandardId =2 };

                //context.Entry(studentNew).State = studentNew.StudentID == 0 ? EntityState.Added : EntityState.Modified;

                //context.SaveChanges();

                //foreach (var entity in context.ChangeTracker.Entries())
                //{
                //    Console.WriteLine("{0}: {1}", entity.Entity.GetType().Name, entity.State);
                //}



                Console.ReadLine();
            }


            Console.WriteLine("Hello");
        }