Last active
July 19, 2019 09:16
-
-
Save wi7a1ian/f350ded5a53d7a3b5bb17c8031c42dc1 to your computer and use it in GitHub Desktop.
Dynamic data read from db using ADO.NET for SQLite in c# #csharp #sqlite
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public IList<ExpandoObject> ReadFromSQLite(string databasePath, string query) | |
{ | |
var results = new List<ExpandoObject>(); | |
using (var connection = new SQLiteConnection($"Data Source={databasePath}")) | |
{ | |
connection.Open(); | |
using (SQLiteCommand cmd = connection.CreateCommand()) | |
{ | |
cmd.CommandText = query; | |
using (SQLiteDataReader reader = cmd.ExecuteReader()) | |
{ | |
while (reader.Read()) | |
{ | |
var obj = new ExpandoObject(); | |
var objDict = obj as IDictionary<string, object>; | |
for (int columnIdx = 0; columnIdx < reader.FieldCount; columnIdx++) | |
{ | |
var propertyName = reader.GetName(columnIdx); | |
if (!reader.IsDBNull(columnIdx)) | |
{ | |
objDict[propertyName] = reader[propertyName]?.ToString(); | |
} | |
else | |
{ | |
objDict[propertyName] = string.Empty; | |
} | |
} | |
results.Add(obj); | |
} | |
} | |
} | |
} | |
return results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment