views:

425

answers:

2

I'm trying to verify if a schema matches the objects I'm initializing.

Is there a way to get the TableName of a class other than simply reflecting the class name?

I am using some class with explicit TableNames

Edit: using Joe's solution I added the case where you don't specify the table name, it could probably use a constraint

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;
}
+2  A: 

If you have something like the following:

[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; }
}

This will get you the table name:

    [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);
        }
    }
looks good I'm going to test it out
Scott Cowan
+1  A: 

You could also use:

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

see this testcase

Mauricio Scheffer