我可以在c#中告诉ActiveRecord类的表名吗?

时间:2008-10-13 16:20:30

标签: c# castle-activerecord

我正在尝试验证架构是否与我正在初始化的对象匹配。

除了简单地反映类名之外,有没有办法获取类的TableName?

我正在使用一些带有显式TableNames的类

编辑:使用Joe的解决方案我添加了你没有指定表名的情况,它可能使用约束

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 个答案:

答案 0 :(得分: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);
        }
    }

答案 1 :(得分:2)

你也可以使用:

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

请参阅this testcase