Россия, г. Ейск |
Опубликован: 01.11.2011 | Уровень: специалист | Доступ: платный
Практическая работа 23:
Создание локальной базы данных для Windows Phone
Создайте папку Model и разместите в ней файл кода AnimalDataContext.cs со следующим содержимым:
using System; using System.ComponentModel; using System.Data.Linq; using System.Data.Linq.Mapping; /* Copyright (c) 2011 Microsoft Corporation. All rights reserved. Use of this sample source code is subject to the terms of the Microsoft license agreement under which you licensed this sample source code and is provided AS-IS. If you did not accept the terms of the license agreement, you are not authorized to use this sample source code. For the terms of the license, please see the license agreement between you and Microsoft. */ namespace LocalDatabaseSample.Model { public class AnimalDataContext : DataContext { // Pass the connection string to the base class. public AnimalDataContext(string connectionString) : base(connectionString) { } // Specify a table for the Animal items. public Table<AnimalItem> Items; // Specify a table for the categories. public Table<AnimalCategory> Categories; } [Table] public class AnimalItem : INotifyPropertyChanged, INotifyPropertyChanging { // Define ID: private field, public property, and database column. private int _AnimalItemId; [Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)] public int AnimalItemId { get { return _AnimalItemId; } set { if (_AnimalItemId != value) { NotifyPropertyChanging("AnimalItemId"); _AnimalItemId = value; NotifyPropertyChanged("AnimalItemId"); } } } // Define item name: private field, public property, and database column. private string _itemName; [Column] public string ItemName { get { return _itemName; } set { if (_itemName != value) { NotifyPropertyChanging("ItemName"); _itemName = value; NotifyPropertyChanged("ItemName"); } } } // Define completion value: private field, public property, and database column. private bool _isComplete; [Column] public bool IsComplete { get { return _isComplete; } set { if (_isComplete != value) { NotifyPropertyChanging("IsComplete"); _isComplete = value; NotifyPropertyChanged("IsComplete"); } } } // Internal column for the associated AnimalCategory ID value [Column] internal int _categoryId; // Entity reference, to identify the AnimalCategory "storage" table private EntityRef<AnimalCategory> _category; // Association, to describe the relationship between this key and that "storage" table [Association(Storage = "_category", ThisKey = "_categoryId", OtherKey = "Id", IsForeignKey = true)] public AnimalCategory Category { get { return _category.Entity; } set { NotifyPropertyChanging("Category"); _category.Entity = value; if (value != null) { _categoryId = value.Id; } NotifyPropertyChanging("Category"); } } // Version column aids update performance. [Column(IsVersion = true)] private Binary _version; #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; // Used to notify that a property changed private void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } #endregion #region INotifyPropertyChanging Members public event PropertyChangingEventHandler PropertyChanging; // Used to notify that a property is about to change private void NotifyPropertyChanging(string propertyName) { if (PropertyChanging != null) { PropertyChanging(this, new PropertyChangingEventArgs(propertyName)); } } #endregion } [Table] public class AnimalCategory : INotifyPropertyChanged, INotifyPropertyChanging { // Define ID: private field, public property, and database column. private int _id; [Column(DbType = "INT NOT NULL IDENTITY", IsDbGenerated = true, IsPrimaryKey = true)] public int Id { get { return _id; } set { NotifyPropertyChanging("Id"); _id = value; NotifyPropertyChanged("Id"); } } // Define category name: private field, public property, and database column. private string _name; [Column] public string Name { get { return _name; } set { NotifyPropertyChanging("Name"); _name = value; NotifyPropertyChanged("Name"); } } // Define the entity set for the collection side of the relationship. private EntitySet<AnimalItem> _Animals; [Association(Storage = "_Animals", OtherKey = "_categoryId", ThisKey = "Id")] public EntitySet<AnimalItem> Animals { get { return this._Animals; } set { this._Animals.Assign(value); } } // Assign handlers for the add and remove operations, respectively. public AnimalCategory() { _Animals = new EntitySet<AnimalItem>( new Action<AnimalItem>(this.attach_Animal), new Action<AnimalItem>(this.detach_Animal) ); } // Called during an add operation private void attach_Animal(AnimalItem Animal) { NotifyPropertyChanging("AnimalItem"); Animal.Category = this; } // Called during a remove operation private void detach_Animal(AnimalItem Animal) { NotifyPropertyChanging("AnimalItem"); Animal.Category = null; } // Version column aids update performance. [Column(IsVersion = true)] private Binary _version; #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; // Used to notify that a property changed private void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } #endregion #region INotifyPropertyChanging Members public event PropertyChangingEventHandler PropertyChanging; // Used to notify that a property is about to change private void NotifyPropertyChanging(string propertyName) { if (PropertyChanging != null) { PropertyChanging(this, new PropertyChangingEventArgs(propertyName)); } } #endregion } }
Создайте папку ViewModel и разместите в ней файл AnimalViewModel.cs со следующим содержимым:
using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; /* Copyright (c) 2011 Microsoft Corporation. All rights reserved. Use of this sample source code is subject to the terms of the Microsoft license agreement under which you licensed this sample source code and is provided AS-IS. If you did not accept the terms of the license agreement, you are not authorized to use this sample source code. For the terms of the license, please see the license agreement between you and Microsoft. */ // Directive for the data model. using LocalDatabaseSample.Model; namespace LocalDatabaseSample.ViewModel { public class AnimalViewModel : INotifyPropertyChanged { // LINQ to SQL data context for the local database. private AnimalDataContext AnimalDB; // Class constructor, create the data context object. public AnimalViewModel(string AnimalDBConnectionString) { AnimalDB = new AnimalDataContext(AnimalDBConnectionString); } // All to-do items. private ObservableCollection<AnimalItem> _allAnimalItems; public ObservableCollection<AnimalItem> AllAnimalItems { get { return _allAnimalItems; } set { _allAnimalItems = value; NotifyPropertyChanged("AllAnimalItems"); } } // Animal items associated with the Birds category. private ObservableCollection<AnimalItem> _BirdsAnimalItems; public ObservableCollection<AnimalItem> BirdsAnimalItems { get { return _BirdsAnimalItems; } set { _BirdsAnimalItems = value; NotifyPropertyChanged("BirdsAnimalItems"); } } // Animal items associated with the Reptiles category. private ObservableCollection<AnimalItem> _ReptilesAnimalItems; public ObservableCollection<AnimalItem> ReptilesAnimalItems { get { return _ReptilesAnimalItems; } set { _ReptilesAnimalItems = value; NotifyPropertyChanged("ReptilesAnimalItems"); } } // Animal items associated with the Fishes category. private ObservableCollection<AnimalItem> _FishesAnimalItems; public ObservableCollection<AnimalItem> FishesAnimalItems { get { return _FishesAnimalItems; } set { _FishesAnimalItems = value; NotifyPropertyChanged("FishesAnimalItems"); } } // A list of all categories, used by the add task page. private List<AnimalCategory> _categoriesList; public List<AnimalCategory> CategoriesList { get { return _categoriesList; } set { _categoriesList = value; NotifyPropertyChanged("CategoriesList"); } } // Query database and load the collections and list used by the pivot pages. public void LoadCollectionsFromDatabase() { // Specify the query for all to-do items in the database. var AnimalItemsInDB = from AnimalItem Animal in AnimalDB.Items select Animal; // Query the database and load all to-do items. AllAnimalItems = new ObservableCollection<AnimalItem>(AnimalItemsInDB); // Specify the query for all categories in the database. var AnimalCategoriesInDB = from AnimalCategory category in AnimalDB.Categories select category; // Query the database and load all associated items to their respective collections. foreach (AnimalCategory category in AnimalCategoriesInDB) { switch (category.Name) { case "Птицы": BirdsAnimalItems = new ObservableCollection<AnimalItem>(category.Animals); break; case "Пресмыкающиеся": ReptilesAnimalItems = new ObservableCollection<AnimalItem>(category.Animals); break; case "Рыбы": FishesAnimalItems = new ObservableCollection<AnimalItem>(category.Animals); break; default: break; } } // Load a list of all categories. CategoriesList = AnimalDB.Categories.ToList(); } // Add an Animal item to the database and collections. public void AddAnimalItem(AnimalItem newAnimalItem) { // Add an Animal item to the data context. AnimalDB.Items.InsertOnSubmit(newAnimalItem); // Save changes to the database. AnimalDB.SubmitChanges(); // Add an Animal item to the "all" observable collection. AllAnimalItems.Add(newAnimalItem); // Add an Animal item to the appropriate filtered collection. switch (newAnimalItem.Category.Name) { case "Птицы": BirdsAnimalItems.Add(newAnimalItem); break; case "Пресмыкающиеся": ReptilesAnimalItems.Add(newAnimalItem); break; case "Рыбы": FishesAnimalItems.Add(newAnimalItem); break; default: break; } } // Remove an Animal task item from the database and collections. public void DeleteAnimalItem(AnimalItem AnimalForDelete) { // Remove the Animal item from the "all" observable collection. AllAnimalItems.Remove(AnimalForDelete); // Remove the Animal item from the data context. AnimalDB.Items.DeleteOnSubmit(AnimalForDelete); // Remove the Animal item from the appropriate category. switch (AnimalForDelete.Category.Name) { case "Птицы": BirdsAnimalItems.Remove(AnimalForDelete); break; case "Пресмыкающиеся": ReptilesAnimalItems.Remove(AnimalForDelete); break; case "Рыбы": FishesAnimalItems.Remove(AnimalForDelete); break; default: break; } // Save changes to the database. AnimalDB.SubmitChanges(); } // Write changes in the data context to the database. public void SaveChangesToDB() { AnimalDB.SubmitChanges(); } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; // Used to notify Silverlight that a property has changed. private void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } #endregion } }
Запустите проект, нажав клавишу F5. Нажмите на кнопку Start, затем выберите пункт SETTINGS:
Выберите пункт Region + Language, В разделе Display language выберите русский язык:
Сохраните настройки.
Вернитесь в приложение LocalDataBaseSample. Поработайте с базой данных.