/// <summary> /// Uses LibraryContext and LibraryContextInitializer to create a new Code First database. /// </summary> public static void CreateAndInitializeDatabase() { //Sets the initializer for the database Database.SetInitializer <LibraryContextCodeFirst>(new LibraryContextInitializer()); //To create the database we must try to access it. Below the code will grab the first book but not do anything with it. using (LibraryContextCodeFirst context = new LibraryContextCodeFirst()) { BookCodeFirst book = (from b in context.Books select b).FirstOrDefault(); //At this point the database will be made from Code First, and concludes the Code First contribution to this app. } }
/// <summary> /// Sets the property of BookCodeFirst objects from an XML file. /// </summary> /// <param name="path"></param> /// <returns></returns> public void GetBookCodeFirstsFromXDocument(string path) { //Get xelements using LINQ var booksXML = (from b in XDocument.Load(path).Descendants("Book") select b).ToList(); List <BookCodeFirst> books = new List <BookCodeFirst>(booksXML.Count); BookCodeFirst book; //Loop through each book entry in the XML file foreach (XElement b in booksXML) { book = new BookCodeFirst(); //Loop through the child XElements in each book foreach (XElement x in b.Elements()) { //Swith is needed for the non-required fields switch (x.Name.ToString()) { case "BookID": book.BookID = int.Parse(b.Element("BookID").Value.Trim()); break; case "ISBN": book.ISBN = b.Element("ISBN").Value.Trim(); break; case "Title": book.Title = b.Element("Title").Value.Trim(); break; case "AuthorID": book.AuthorID = int.Parse(b.Element("AuthorID").Value.Trim()); break; case "NumPages": book.NumPages = int.Parse(b.Element("NumPages").Value.Trim()); break; case "Subject": book.Subject = b.Element("Subject").Value.Trim(); break; case "Description": book.Description = b.Element("Description").Value.Trim(); break; case "Publisher": book.Publisher = b.Element("Publisher").Value.Trim(); break; case "YearPublished": book.YearPublished = b.Element("YearPublished").Value.Trim(); break; case "Language": book.Language = b.Element("Language").Value.Trim(); break; case "NumberOfCopies": book.NumberOfCopies = int.Parse(b.Element("NumberOfCopies").Value.Trim()); break; } } books.Add(book); } Books = books; }