【问题标题】:How do I get a Sqlite Table attribute from a Class?如何从类中获取 Sqlite 表属性?
【发布时间】:2016-06-14 19:43:10
【问题描述】:

我想从我的班级获得一个 Sqlite Table 属性。

我有一种方法可以检查来自here 的表是否存在:

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 属性?

附言。我正在使用 PCL(可移植类库)

【问题讨论】:

    标签: c# sqlite class attributes


    【解决方案1】:

    知道了。只需要在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;
    }
    

    【讨论】:

      【解决方案2】:

      这是 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;
      }
      

      Source

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-27
        • 2016-01-06
        • 1970-01-01
        • 1970-01-01
        • 2010-10-18
        • 1970-01-01
        相关资源
        最近更新 更多