2008-10-13 68 views
1

我想驗證模式是否與我正在初始化的對象匹配。我可以告訴c#中的ActiveRecord類的表名嗎?

有沒有一種方法可以獲取類的TableName而不是簡單地反映類名?

我使用一些類明確表名

編輯:使用喬的解決方案,我加入,你不指定表名的情況下,很可能使用約束

public string find_table_name(object obj) 
{ 
     object[] attribs = obj.GetType().GetCustomAttributes(typeof(Castle.ActiveRecord.ActiveRecordAttribute), false); 

     if (attribs != null) 
     { 
      ActiveRecordAttribute attrib = (Castle.ActiveRecord.ActiveRecordAttribute) attribs[0]; 
      if (attrib.Table != null) 
       return attrib.Table; 
      return obj.GetType().Name; 
     } 
    return null; 
} 

回答

3

如果您有像下面這樣:

[ActiveRecord(Table = "NewsMaster")] 
public class Article 
{ 
    [PrimaryKey(Generator = PrimaryKeyType.Identity)] 
    public int NewsId { get; set; } 

    [Property(Column = "NewsHeadline")] 
    public string Headline { get; set; } 

    [Property(Column = "EffectiveStartDate")] 
    public DateTime StartDate { get; set; } 

    [Property(Column = "EffectiveEndDate")] 
    public DateTime EndDate { get; set; } 

    [Property] 
    public string NewsBlurb { get; set; } 
} 

這將讓你的表名:

[Test] 
    public void Can_get_table_name() 
    { 
     var attribs = typeof(Article).GetCustomAttributes(typeof(Castle.ActiveRecord.ActiveRecordAttribute), false); 

     if (attribs != null) 
     { 
      var attrib = (Castle.ActiveRecord.ActiveRecordAttribute) attribs[0]; 
      Assert.AreEqual("NewsMaster", attrib.Table); 
     } 
    } 
+0

看起來不錯,我要測試它 – 2008-10-14 05:10:37

+0

可以這樣反向做? IE:我想通過(字符串)ModelClassName獲取模塊,以便我可以去ModelClassName [] all_tag = ActiveRecordBase .FindAll(); ??我一直在研究另一個問題,我認爲需要通過使用相同的解決方案來完成,但是要倒退。希望這是有道理的。問題在這裏。 http://stackoverflow.com/q/8332556/746758 – 2011-12-20 15:58:36

2

您還可以使用:

ActiveRecordModel.GetModel(typeof(Article)).ActiveRecordAtt.Table 

看到this testcase

相關問題