我如何从类获得一个Sqlite表属性
本文关键字:一个 Sqlite 属性 | 更新日期: 2023-09-27 18:05:40
我想从我的类中获得一个Sqlite Table
属性。
我有一个方法来检查表是否存在:
var info = database.Connection.GetTableInfo(typeof(Customer).Name);
if (info.Any())
{
//do stuff with table
}
其中Customer
为:
[Table("Customer")]
public class Customer
{
//class stuff
}
现在我的方法将工作得很好,因为它是,但我想把它链接到Table
属性,而不是类名,以防我改变表名在未来。
我如何从我的类获得我的Table
属性?
p。我正在使用PCL(便携式类库)
明白了。只需要在我正在寻找的属性类型的Type
和提要上使用GetCustomAttributes方法。所以它变成了:
string tableName = typeof(Customer).Name;
var customAttributes = typeof(Customer).GetCustomAttributes(typeof(SQLite.Net.Attributes.TableAttribute),false);
if (customAttributes.Count() > 0)
{
tableName = (customAttributes.First() as SQLite.Net.Attributes.TableAttribute).Name;
}
以下是PCL的解决方案:
using System.Reflection;
string tableName = typeof(MyClass).Name;
var customAttributes = typeof(MyClass).GetTypeInfo().GetCustomAttributes<SQLite.Net.Attributes.TableAttribute>();
if(customAttributes.Count() > 0)
{
tableName = customAttributes.First().Name;
}
源