2008-10-13 73 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

相关问题