/// <summary> /// Update the changes to the data at the server side /// </summary> /// <param name="context">The DataServiceContext to be updated. /// </param> /// <returns>Whether the update is successful.</returns> private static bool UpdateData(DataServiceContext context) { try { // Get the response from the DataServiceContext update // operation DataServiceResponse response = context.SaveChanges(); bool isSucess = false; foreach (var r in response) { // If response status code shows the update fails // return false if (!r.StatusCode.ToString().StartsWith("2")) { return(false); } else { isSucess = true; } } // The update is successful return(isSucess); } catch (Exception ex) { // Retrieve the exception information if there is some // DataServiceException is thrown at the server side if (ex.InnerException is DataServiceClientException) { // Parse the DataServieClientException InnerDataServiceException innerException = ParseDataServiceClientException(ex.InnerException. Message); // Display the DataServiceClientException message if (innerException != null) { Console.WriteLine("DataServiceException Message: " + innerException.Message); } } else { Console.WriteLine("The update operation throws the error: " + ex.Message); } return(false); } }
static void Main(string[] args) { try { // Update and query relational database via LINQ to Entities UpdateQueryRelationalDataByLinqToEntities(); // Update and query relational database via LINQ to SQL UpdateQueryRelationDataByLinqToSQL(); // Query relational database via ADO.NET query options and // custom service operations QueryRelationDataByQueryOptionsAndServiceOperations(); // Insert and query non-relational data UpdateQueryNonRelationalData(); } catch (Exception ex) { // Retrieve the exception information if there is some // DataServiceException is thrown at the server side if (ex.InnerException is DataServiceClientException) { // Parse the DataServieClientException InnerDataServiceException innerException = ParseDataServiceClientException(ex.InnerException. Message); // Display the DataServiceClientException message if (innerException != null) { Console.WriteLine("DataServiceException Message: " + innerException.Message); } } else { Console.WriteLine("The application throws the error: " + ex.Message); } } finally { Console.ReadLine(); } }
/// <summary> /// Update and query relational database via LINQ to Entities /// </summary> private static void UpdateQueryRelationalDataByLinqToEntities() { Console.WriteLine("======================================"); Console.WriteLine("Update and query data via LINQ to Entities:"); Console.WriteLine("======================================"); ///////////////////////////////////////////////////////////////// // Initialize the DataService object for ADO.NET Entity Data // Model // SchoolLinqToEntitiesService.SQLServer2005DBEntities svc = new SchoolLinqToEntitiesService.SQLServer2005DBEntities(new Uri( schoolLinqToEntitiesUri)); ///////////////////////////////////////////////////////////////// // Insert wrong data which the server side handles // // Create a wrong instructor SchoolLinqToEntitiesService.Person wrongInstructor = new SchoolLinqToEntitiesService.Person() { FirstName = "Riquel", LastName = "Dong", HireDate = DateTime.Now, // Set invalid value for the PersonCategory PersonCategory = 3 }; Console.Write("Insert wrong Person information into database..."); // Update the changes to the database if (UpdateData(svc)) { Console.WriteLine("Successfully!"); } else { Console.WriteLine("Failed!"); try { // Get the person update exception svc.Execute <SchoolLinqToEntitiesService.Person>(new Uri( "/GetPersonUpdateException", UriKind.Relative)); } catch (Exception updateException) { // Retrieve the exception information if there is some // DataServiceException is thrown at the server side if (updateException.InnerException is DataServiceClientException) { // Parse the DataServieClientException InnerDataServiceException innerException = ParseDataServiceClientException( updateException.InnerException.Message); // Display the DataServiceClientException message if (innerException != null) { Console.WriteLine("DataServiceException Message: " + innerException.Message); } } } // Detach the incorrect Person object svc.Detach(wrongInstructor); } ///////////////////////////////////////////////////////////////// // Insert relational data into database // // Create a new instructor SchoolLinqToEntitiesService.Person newInstructor = new SchoolLinqToEntitiesService.Person() { FirstName = "Riquel", LastName = "Dong", HireDate = DateTime.Now, PersonCategory = 2 }; // Create a new course SchoolLinqToEntitiesService.Course newCourse1 = new SchoolLinqToEntitiesService.Course() { CourseID = 5010, Title = "Network", Credits = 4, DepartmentID = 1 }; // Create a new course SchoolLinqToEntitiesService.Course newCourse2 = new SchoolLinqToEntitiesService.Course() { CourseID = 5020, Title = "Database", Credits = 3, DepartmentID = 1 }; // Add the newly-created instructor into context svc.AddToPerson(newInstructor); // Add the newly-created courses into context svc.AddToCourse(newCourse1); svc.AddToCourse(newCourse2); // Add relationships to the newly-created instructor and courses svc.AddLink(newCourse1, "Person", newInstructor); svc.AddLink(newCourse2, "Person", newInstructor); Console.Write("Insert related data into database..."); // Update the changes to the database if (UpdateData(svc)) { Console.WriteLine("Successfully!"); } else { Console.WriteLine("Faild!"); } Console.WriteLine(); ///////////////////////////////////////////////////////////////// // Query single data table via LINQ // // Get all the teachers whose first name is 'Roger' // LINQ operator and ADO.NET Data Service query option comparison // 'where'(LINQ) <==> 'filter'(Query Option) var teachers = from p in svc.Person where p.PersonCategory == 2 && p.FirstName == "Roger" select p; Console.WriteLine("All the teachers whose first name is 'Roger':"); // Display the query results foreach (var t in teachers) { Console.WriteLine("{0} {1}", t.FirstName, t.LastName); } Console.WriteLine(); // Get the third and fourth newly-enrolled students // LINQ operator and ADO.NET Data Service query option comparison // 'where'(LINQ) <==> 'filter'(Query Option) // 'orderby' (LINQ) <==> 'orderby' (Query Option) // 'Skip' (LINQ) <=> 'skip' (Query Option) // 'Take' (LINQ) <==> 'top' (Query Option) var students = (from p in svc.Person where p.PersonCategory == 1 orderby p.EnrollmentDate descending select p).Skip(2).Take(2); Console.WriteLine("The third and fourth newly-enrolled students:"); // Display the query results foreach (var s in students) { Console.WriteLine("{0} {1}", s.FirstName, s.LastName); } Console.WriteLine(); ///////////////////////////////////////////////////////////////// // Query relational data tables via LINQ and custom service // operation // // Get the instructors whose name is 'Riquel Dong' var instructors = from p in svc.Person where p.LastName == "Dong" && p.FirstName == "Riquel" select p; // Get all the courses that 'Riquel Dong' owns foreach (var i in instructors) { // Call the service operation CoursesByPersonID to get the // certain person's courses based on primary key PersonID Uri uri = new Uri(String.Format("/CoursesByPersonID?ID={0}", i.PersonID), UriKind.Relative); // Exceute the URL to the retrieve the course list var courses = svc.Execute <SchoolLinqToEntitiesService.Course> (uri); Console.WriteLine("The instructor {0}'s couses:", i.FirstName + " " + i.LastName); // Display the query results foreach (var c in courses) { Console.WriteLine("Course Title: {0}, Credits: {1}", c.Title, c.Credits); } } Console.WriteLine(); }