1

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

除了简单地反映类名之外,还有其他方法可以获取类的 TableName 吗?

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

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

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

2 回答 2

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);
        }
    }
于 2008-10-13T16:58:21.017 回答
2

您还可以使用:

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

看到这个测试用例

于 2008-11-28T12:18:51.030 回答