使用表中的多行作为属性

时间:2018-09-29 20:24:58

标签: c# entity-framework sqlite linq-to-sql system.data.sqlite

我正在使用System.Data.Sqlite库处理sqlite数据库。我有“元数据”表,看起来像这样:

Table screenshot

它并不总是包含所有这些行和字段,并且还可以有很多可选的行和字段。 通常,我将这些字段作为属性(通过阅读查询和反射获得),作为我的课程:

class MetadataTable
{
    public string Version { get; set; }
    public string Timestamp { get; set; }
    public string Author { get; set; }
    public string Location { get; set; }

    public MetadataTable(string pathToDb)
    {
        using (SQLiteConnection connection = new SQLiteConnection($"Data Source={pathToDb};Version=3;"))
        {
            try
            {
                connection.Open();
            }
            catch (Exception)
            {
                throw new Exception("Unable to open database.");
            }

            using (SQLiteCommand command = new SQLiteCommand(connection))
            {
                command.CommandText = "SELECT key, value FROM metadata;";
                using (SQLiteDataReader reader = command.ExecuteReader())
                {
                    List<string> propertyNames = new List<string>();
                    List<string> propertyValues = new List<string>();
                    while (reader.Read())
                    {
                        propertyNames.Add(reader[0].ToString());
                        propertyValues.Add(reader[1].ToString());
                    }

                    for (int i = 0; i < propertyNames.Count; i++)
                        propertyNames[i] = propertyNames[i].ToLower().First().ToString().ToUpper()
                                         + propertyNames[i].Substring(1);
                    for (int i = 0; i < propertyValues.Count; i++)
                        typeof(MetadataTable).GetProperty(propertyNames[i])?.SetValue(this, propertyValues[i]);
                }
            }
        }
    }
}

以及如何从Main()调用它:

string pathToDb = "D:/Downloads/mytest.db";
MetadataTable metadataTable = new MetadataTable(pathToDb);
Console.WriteLine($"Version:{metadataTable.Version}, Author:{metadataTable.Author}, " +
                  $"Timestamp:{metadataTable.Timestamp}, Location:{metadataTable.Location ?? "Not specified"}");

最近,我决定尝试使用LINQ to SQL,并为我的表编写了一个简单的类:

[Table(Name = "metadata")]
class Metadata
{
    [Column(Name = "key")]
    public string Key { get; set; }
    [Column(Name = "value")]
    public string Value { get; set; }
}

这就是我在Main()中阅读它的方式:

using (SQLiteConnection connection = new SQLiteConnection($"Data Source={pathToDb};Version=3;"))
{
    using (DataContext context = new DataContext(connection))
    {
        Table<Metadata> metadataFields = context.GetTable<Metadata>();
        foreach (Metadata metadataField in metadataFields)
            Console.WriteLine($"Key:{metadataField.Key}, Value:{metadataField.Value}");
    }
}

我觉得这非常方便,但是在没有使用反射的情况下,是否有相同的便捷方式来处理行/字段作为属性(例如上面的MetadataTable代码)?

还有,顺便说一句,EntityFramework更适合该任务(并且性能更高吗?)?之前我没有使用LINQ to Entity或LINQ to SQL,所以先学习什么并没有什么大不同。

0 个答案:

没有答案