3

Windows Phone 7.1支持SQL Server CE和LINQ to SQL,以及通過DatabaseSchemaUpdater升級數據庫。Windows Phone SQL Server CE - 檢索基礎數據庫模式以進行升級

在其他平臺上,我會讀取數據庫模式表(例如sys.objects)以查看當前模式並確定需要升級的表/列。

鑑於Windows Phone上不允許直接SQL訪問,如何檢索當前數據庫模式?

+0

但即使具有模式知識,也不能添加任何表/列,因爲你不能執行直接的SQL代碼。請參閱以下步驟:演練:更新Windows Phone的本地數據庫應用程序http://msdn.microsoft.com/zh-cn/library/hh394022(v=VS.92).aspx – ErikEJ

+0

您可以使用'DatabaseSchemaUpdater' 。我只需要通過'DatabaseSchemaUpdater'找到我需要添加的模式。 –

+0

但爲什麼不使用版本號? – ErikEJ

回答

1

SQL Server CE仍然包含INFORMATION_SCHEMA.TABLESINFORMATION_SCHEMA.COLUMNS表,但訪問它們有點棘手,因爲不允許直接SQL訪問。

但是,您可以創建一個DataContext映射到這些表:

public class SchemaContext : DataContext 
{ 
    public SchemaContext() 
     : base("Data Source=isostore:/Database.sdf") 
    { 
     if (!this.DatabaseExists()) 
     { 
      throw new InvalidOperationException("Cannot use the SchemaContext on a database which doesn't exist"); 
     } 
    } 

    public Table<Table> Tables; 
    public Table<Column> Columns; 

    [Table(Name = "INFORMATION_SCHEMA.Columns")] 
    public class Column 
    { 
     [Column(Name = "TABLE_NAME")] 
     public string TableName { get; set; } 

     [Column(Name = "COLUMN_NAME")] 
     public string Name { get; set; } 

     [Column(Name = "DATA_TYPE")] 
     public string DataType { get; set; } 

     [Column(Name = "ORDINAL_POSITION")] 
     public int OrdinalPosition { get; set; } 

     [Column(Name = "IS_NULLABLE")] 
     public string IsNullableString { get; set; } 

     public bool IsNullable 
     { 
      get { return this.IsNullableString == "YES"; } 
      set { this.IsNullableString = value ? "YES" : "NO"; } 
     } 

    } 

    [Table(Name = "INFORMATION_SCHEMA.Tables")] 
    public class Table 
    { 
     [Column(Name = "TABLE_NAME")] 
     public string Name { get; set; } 

     [Column(Name = "TABLE_TYPE")] 
     public string Type { get; set; } 
    } 
} 

然後,您可以用下面的代碼讀取架構:

using (var schemaContext = new SchemaContext()) 
{ 
    foreach (var table in schemaContext.Tables) 
    { 

    } 
} 

創建一個單獨的上下文是很重要的這些表,否則DataContext.CreateDatabase調用將嘗試創建這些模式表,這將失敗。

0

有一個Walkthrough for Updating a Local Database Application for Windows Phone on MSDN主張在DatabaseSchemaUpdater使用DatabaseSchemaVersion - 即:

// Set the new database version. 
DatabaseSchemaUpdater dbUpdater = db.CreateDatabaseSchemaUpdater(); 
dbUpdater.DatabaseSchemaVersion = APP_VERSION; 
dbUpdater.Execute(); 

您可以查詢版本,添加在每個版本中增加了位,而不必擔心當前架構(畢竟,只要你記得保持版本號更新正確,它就會是一個已知的配置。)

+0

正如我在上面的評論鏈接中提到的... – ErikEJ

相關問題