如果模式名称中有点,如何为SQLite导出NHibernate模式?

时间:2011-08-11 08:50:18

标签: unit-testing sqlite fluent-nhibernate nunit nhibernate-mapping

我正在尝试使用Fluent NHibernate as shown here设置SQLite进行单元测试,但是没有像我预期的那样生成表名。

有些表格中包含带点的模式,似乎打破了这一代。 (Dots与我在生产环境中使用的Microsoft SQL Server完美配合。)

示例:

[Foo.Bar.Schema].[TableName]

结果:

TestFixture failed: System.Data.SQLite.SQLiteException : SQLite error
unknown database Foo

如何指示SQLite将点转换为下划线或其他内容以便我可以运行单元测试?

(我尝试在模式名称中添加括号但没有成功)

1 个答案:

答案 0 :(得分:1)

您可以使用约定 http://wiki.fluentnhibernate.org/Conventions

*更新

public static class PrivatePropertyHelper
    {
        // from http://stackoverflow.com/questions/1565734/is-it-possible-to-set-private-property-via-reflection
        public static T GetPrivatePropertyValue<T>(this object obj, string propName)
        {
            if (obj == null) throw new ArgumentNullException("obj");
            PropertyInfo pi = obj.GetType().GetProperty(propName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            if (pi == null) throw new ArgumentOutOfRangeException("propName", string.Format("Property {0} was not found in Type {1}", propName, obj.GetType().FullName));
            return (T)pi.GetValue(obj, null);
        }
    }

public class CustomTableNameConvention : IClassConvention
{
    // Use this to set schema to specific value
    public void Apply(FluentNHibernate.Conventions.Instances.IClassInstance instance)
    {
        instance.Schema("My_NEw_Schema");
        instance.Table(instance.EntityType.Name.CamelToUnderscoreLower());
    }


    // Use this to alter the existing schema value.
    // note that Schema is a private property and you need reflection to get it
    public void Apply(FluentNHibernate.Conventions.Instances.IClassInstance instance)
    {          
        instance.Schema(instance.GetPrivatePropertyValue<string>("Schema").Replace(".", "_"));
        instance.Table(instance.EntityType.Name.CamelToUnderscoreLower());
    }
}

您必须只使用其中一种Apply方法。

*更新2 我不知道我会推荐这个,但如果你想尝试这似乎工作。更多的反思:))

    public static void SetSchemaValue(this object obj, string schema)
    {

        var mapping_ref  = obj.GetType().GetField("mapping", BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.GetField | BindingFlags.NonPublic).GetValue(obj);

        var mapping = mapping_ref as ClassMapping;
        if (mapping != null)
        {
            mapping.Schema = schema;
        }
    }


    public void Apply(FluentNHibernate.Conventions.Instances.IClassInstance instance)
    {
        var schema = instance.GetPrivatePropertyValue<string>("Schema");
        if (schema == null)
        {
            instance.Schema("My_New_Schema");
        }
        else
        {
            instance.SetSchemaValue("My_New_Schema");
        }
    }
相关问题