// 插入新的person到现存的course public static void InsertPerson() { using (EFM2MEntities context = new EFM2MEntities()) { Person person = new Person() { FirstName = "Ji", LastName = "Zhou" }; person.Course.Add(context.Course.FirstOrDefault()); context.AddToPerson(person); try { Console.WriteLine("Inserting Person {0} {1} .", person.FirstName, person.LastName); context.SaveChanges(); Query(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
// 插入新的person包括新的course public static void InsertPersonWithCourse() { using (EFM2MEntities context = new EFM2MEntities()) { Person person = new Person() { FirstName = "Yichun", LastName = "Feng" }; Course course = new Course() { CourseID = 2208, Title = "UML" }; person.Course.Add(course); context.AddToPerson(person); try { Console.WriteLine("Inserting Person {0} {1} with course " + "{2}.", person.FirstName, person.LastName, course.Title); context.SaveChanges(); Query(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
// 更新一个现存的person public static void UpdatePerson() { using (EFM2MEntities context = new EFM2MEntities()) { Person person = new Person(); person.PersonID = 34; context.AttachTo("Person", person); person.FirstName = "Monica"; Course course = new Course() { CourseID = 2209, Title = "Operating System" }; person.Course.Add(course); try { Console.WriteLine( "Modifying Person 34's last to {0} and add course {1}" + " to it", person.LastName, course.Title); context.SaveChanges(); Query(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }