2017-07-18 30 views
2

表結構如何檢索xamarin中本地數據庫的字符串值?

[Table(TableConst.TABLE_BRANDING)] 
public class BrandingInfoModel 
{ 
    public int id { get; set; } 
    public string title { get; set; } 
    public string primary_color { get; set; } 
    public string secondary_color { get; set; } 
    public string tertiary_color { get; set; } 
} 

方法,從數據庫

public string GetColorResourceFromDatabase(string key) 
    { 
     try 
     { 

      string value = mSqlConnection.Query<string>("SELECT " + key + " FROM data").ToString(); 
      return value; 

     } 
     catch (Exception e) 
     { 
      string error = e.Message; 
      return null; 
     } 

    } 

我寫了返回基於本地數據庫中的值來選擇查詢的方法來獲取資源。但它返回null。

+0

分享你的'數據'表結構 –

+0

如果KEY是你想要選擇的項目的PK,那麼你的SQL語法是不正確的。 – Jason

+0

Query方法的通用參數指定要爲每行創建的對象的類型(您告訴它使用字符串)。它可以是你的表類或其公共屬性**匹配查詢返回的列的任何其他類。您不能將列值強制爲字符串對象,因爲它沒有公共屬性(至少不使用Query方法)。另請注意,您正在運行的查詢有可能返回多行。我不知道你爲什麼試圖在行列表上調用ToString。 –

回答

4

我已經試過這樣

//Get resource from Brading table 
    public BrandingInfoModel GetResourceFromDatabase(string key) 
    { 
     try 
     { 
      //string value = (from i in mSqlConnection.Table<BrandingInfoModel>() select i.menu_text_color).ToString(); 

      var queryResult = mSqlConnection.Query<BrandingInfoModel>("SELECT " + key + " FROM " + TableConst.TABLE_BRANDING).FirstOrDefault(); 
      return queryResult; 

     } 
     catch (Exception e) 
     { 
      string error = e.Message; 
      return null; 
     } 

    } 

它返回所需的輸出。

0

而不是使用SQL查詢來執行選擇。請考慮使用Linq查詢來達到相同的結果。

例如,如果你想選擇了行並取得編號的primary_color:

var rowData = mSqlConnection.Table<BrandingInfoModel>() 
          .FirstOrDefault(i => i.id == 123); 
if (rowData != null) 
{ 
    return rowData.primary_color; 
} 
相關問題