天道酬勤,学无止境

NHibernate Validator not integrating with Fluent NHibernate

I'm having some trouble getting NHV to work with Fluent NHibernate. A unit test that I have that has an entity that SHOULD be failing validation ends up throwing an ADO exception. I have NHV configured the following way:

    private static void Init()
    {
            _SessionFactory = Fluently.Configure()
              .Database(MsSqlConfiguration.MsSql2005.ConnectionString(connectionString)
                  .ShowSql())
              .Mappings(m =>
                  m.FluentMappings.AddFromAssemblyOf<SessionFactory>()
                  .ExportTo(pathToExportMappingsTo))
              .ProxyFactoryFactory("NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu")
              .ExposeConfiguration(ConfigureNhibernateValidator)
              .BuildSessionFactory();
    }

    private static void ConfigureNhibernateValidator(Configuration config)
    {
        var nhvConfiguration = new NHibernate.Validator.Cfg.Loquacious.FluentConfiguration();
        nhvConfiguration
           .SetDefaultValidatorMode(ValidatorMode.OverrideAttributeWithExternal)
           .Register(Assembly.Load("Business.Objects")
           .ValidationDefinitions())
           .IntegrateWithNHibernate
               .RegisteringListeners();

        ValidatorEngine validatorEngine = new ValidatorEngine();
        validatorEngine.Configure(nhvConfiguration);

        ValidatorInitializer.Initialize(config, validatorEngine);
    }

I've looked over this configuration several times now and scoured the internet to try and find out what's wrong with this. I've also looked at examples provided in the NHV source but I haven't been able to figure out why my unit test does not throw an InvalidStateException. I have a unit test to validate the same entity that should be failing that validates it directly via the validation engine and this works.

Does anyone see anything wrong with the above configuration?

I'm using NHibernate 3.1, NHibernate Validator 1.3 and Fluent NHibernate 1.2.0.712

评论

I debugged this and it seemed that when it went to validate my entity it was initialize my validator engine again. I corrected this by changing the ConfigureNhibernateValidator(Configuration config) method above to the following (the key here was to set the SharedEngineProvider):

    private static void ConfigureNhibernateValidator(Configuration config)
    {
        var provider = new NHibernateSharedEngineProvider();
        NHibernate.Validator.Cfg.Environment.SharedEngineProvider = provider;

        var nhvConfiguration = new NHibernate.Validator.Cfg.Loquacious.FluentConfiguration();
        nhvConfiguration
           .SetDefaultValidatorMode(ValidatorMode.OverrideAttributeWithExternal)
           .Register(Assembly.Load("Business.Objects")
           .ValidationDefinitions())
           .IntegrateWithNHibernate
               .AvoidingDDLConstraints()
               .RegisteringListeners();

        ValidatorEngine validatorEngine = NHibernate.Validator.Cfg.Environment.SharedEngineProvider.GetEngine();
        validatorEngine.Configure(nhvConfiguration);

        ValidatorInitializer.Initialize(config, validatorEngine);
    }

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • Fluent NHibernate enforce Not Nullable on Foreign Key Reference
    Just getting my feet wet with some Fluent NHibernate AutoMap conventions, and ran into something I couldn't figure out. I assume I'm just not looking in the right place... Basically trying to enforce NOT-NULL on the "many" side of the one to many relationship. It seems, using the automapping, it always makes the parent property Id nullable in the database. I did some searching on StackOverFlow and found similar questions, but nothing relating to AutoMapping and Conventions though (unless I missed it). Quick example... public class Group // One Group { public Group() { this.Jobs = new List<Job>
  • 如何配置Fluent NHibernate将查询输出到跟踪或调试而不是控制台?(How to configure Fluent NHibernate to output queries to Trace or Debug instead of Console?)
    问题 如何配置Fluent NHibernate将查询输出到跟踪或调试而不是控制台? 我正在使用MsSqlConfiguration.MsSql2008.ShowSql()但它没有参数,在Google上找不到任何内容。 回答1 我可以从世界各地的论坛和博客文章中看到,在我之前还有很多其他人在寻找一种准备执行的SQL语句的方法。 答案通常是“不可以”或“不应该”。 无论我是否应该,这就是我想要的。 经过数小时的搜索,调查和失败的尝试,终于我想到了这一点。 写一个拦截器: using NHibernate; using System.Diagnostics; public class SqlStatementInterceptor : EmptyInterceptor { public override NHibernate.SqlCommand.SqlString OnPrepareStatement(NHibernate.SqlCommand.SqlString sql) { Trace.WriteLine(sql.ToString()); return sql; } } 当然,您不必在这里使用Trace.WriteLine() ,也可以将其写入日志文件,或者其他任何需要的文件。 在您的连接管理器中,像这样连接您的拦截器: protected virtual void
  • 流利的NHibernate多对多(Fluent NHibernate Many-to-Many)
    问题 我正在使用Fluent NHibernate,但在与我的一个班级建立多对多关系时遇到了一些问题。 这可能是一个愚蠢的错误,但为了使它正常工作,我已经被卡住了一点。 无论如何,我有几个具有很多关系的课程。 public class Person { public Person() { GroupsOwned = new List<Groups>(); } public virtual IList<Groups> GroupsOwned { get; set; } } public class Groups { public Groups() { Admins= new List<Person>(); } public virtual IList<Person> Admins{ get; set; } } 映射看起来像这样 人: ... HasManyToMany<Groups>(x => x.GroupsOwned) .WithTableName("GroupAdministrators") .WithParentKeyColumn("PersonID") .WithChildKeyColumn("GroupID") .Cascade.SaveUpdate(); 群组:... HasManyToMany<Person>(x => x.Admins) .WithTableName
  • Fluent NHibernate Many-to-Many
    I am using Fluent NHibernate and having some issues getting a many to many relationship setup with one of my classes. It's probably a stupid mistake but I've been stuck for a little bit trying to get it working. Anyways, I have a couple classes that have Many-Many relationships. public class Person { public Person() { GroupsOwned = new List<Groups>(); } public virtual IList<Groups> GroupsOwned { get; set; } } public class Groups { public Groups() { Admins= new List<Person>(); } public virtual IList<Person> Admins{ get; set; } } With the mapping looking like this Person: ... HasManyToMany
  • How can you create Clustered Indexes with Fluent NHibernate?
    I am using Fluent-NHibernate (with automapping) to generate my tables but would like to choose a different clustered index than the ID field which is used by default. How can you create clustered indexes with Fluent NHibernate on a field other than the default Primary Key field? The primary reasoning behind this is simple. I am using Guids for my primary key fields. By default, NHibernate creates clustered indexes on the primary key fields. Since Guids are usually not sequential, clustering on the primary key field causes a performance issue. As we all know, appending records at the end of a
  • Programming to interfaces while mapping with Fluent NHibernate
    I have been whipped into submission and have started learning Fluent NHibernate (no previous NHibernate experience). In my project, I am programming to interfaces to reduce coupling etc. That means pretty much "everything" refers to the interface instead of the concrete type (IMessage instead of Message). The thought behind this is to help make it more testable by being able to mock dependencies. However, (Fluent) NHibernate doesn't love it when I try to map to interfaces instead of concrete classes. The issue is simple - according to the Fluent Wiki, it is smart to define the ID field of my
  • Fluent NHibernate: How to create one-to-many bidirectional mapping?
    Basic question: How to I create a bidirectional one-to-many map in Fluent NHibernate? Details: I have a parent object with many children. In my case, it is meaningless for the child to not have a parent, so in the database, I would like the foreign key to the parent to have NOT NULL constraint. I am auto-generating my database from the Fluent NHibernate mapping. I have a parent with many child objects like so: public class Summary { public int id {get; protected set;} public IList<Detail> Details {get; protected set;} } public class Detail { public int id {get; protected set;} public string
  • Map Enum as Int with Fluent NHibernate and NHibernate 3
    I used this How do you map an enum as an int value with fluent NHibernate? to map in the past but I've recently upgraded to NHibernate 3 and this doesn't seem to work anymore. I've put breakpoints in my EnumConvention class and they're not being hit. The query that is hitting the database has the enum as a string which is the default configuration. How does this work with NHibernate 3? Update Here is part of the mapping file that is generated: <property name="ComponentType" type="FluentNHibernate.Mapping.GenericEnumMapper`1[[...ComponentType, ..., Version=1.0.0.0, Culture=neutral
  • Eager Loading Using Fluent NHibernate/Nhibernate & Automapping
    I have a requirement to load a complex object called Node...well its not that complex...it looks like follows:- A Node has a reference to EntityType which has a one to many with Property which in turn has a one to many with PorpertyListValue public class Node { public virtual int Id { get; set; } public virtual string Name { get; set; } public virtual EntityType Etype { get; set; } } public class EntityType { public virtual int Id { get; set; } public virtual string Name { get; set; } public virtual IList<Property> Properties { get; protected set; } public EntityType() { Properties = new List
  • 流利的NHibernate列映射与保留字(Fluent NHibernate Column Mapping with Reserved Word)
    问题 我已经读过,使用反勾号`应该允许使用保留字。 我正在使用SQL Server和Fluent NHibernate,并且具有列名“ File”。 如果我用 "`File" 它尝试使用 [Fil] 因此它正确地添加了括号,但从末尾删除了“ e”。 如果我将其映射为 "`Filee" 它用 [File] 正确地。 我是在做错什么,还是NHibernate或Fluent Nhibernate中的错误? 回答1 您需要在两面都放`,如下所示: "`File`" 正如@Astaar所说,完整的语法是: Map(x => x.File).Column("`File`"); 回答2 完全清楚地说,确切的语法是 Map(x => x.File).Column("`File`"); 回答3 此处涵盖了一些非手动配置选项:NHibernate:在模式导出中是否强制使用方括号? 以及替代方法:Fluent NHibernate和PostgreSQL,SchemaMetadataUpdater.QuoteTableAndColumns-System.NotSupportedException:不支持指定的方法 例如SchemaMetadataUpdater.QuoteTableAndColumns(cfg) ,在FluentNhibernate中看起来像 var config = Fluently
  • 在Fluent Nhibernate中设置实体和关系上的缓存?(Set up caching on entities and relationships in Fluent Nhibernate?)
    问题 有没有人举过一个例子,说明如何设置以及要在流畅的nhibernate中缓存哪些实体。 既使用流利的映射又使用自动映射? 一对多和多对多的实体关系也一样吗? 回答1 我一直在类似的情况下工作,我只想缓存特定的元素,并希望这些元素在启动时被加载一次,并保留在缓存中,直到应用程序关闭。 这是只读缓存,用于填充国家/地区列表,以便用户可以从列表中选择其国家/地区。 我使用fluentNhibernate映射,并使用Cache.readonly()定义了Country我的班级。 public class CountryMap : ClassMap<Country> { public CountryMap() { Schema("Dropdowns"); Cache.ReadOnly(); // Class mappings underneath } } 我的用户类映射如下所示: public class UserMap : ClassMap<User> { Id(x => x.Id).Column("UserId"); Map(x => x.FirstName); Map(x => x.LastName); References(x => x.Country) .Column("CountryId"); } 我手动将Fluent Nhibernate配置为使用二级缓存。 因此
  • Inheritance Mapping with Fluent NHibernate
    Given the following scenario, I want map the type hierarchy to the database schema using Fluent NHibernate. I am using NHibernate 2.0 Type Hierarchy public abstract class Item { public virtual int ItemId { get; set; } public virtual string ItemType { get; set; } public virtual string FieldA { get; set; } } public abstract class SubItem : Item { public virtual string FieldB { get; set; } } public class ConcreteItemX : SubItem { public virtual string FieldC { get; set; } } public class ConcreteItemY : Item { public virtual string FieldD { get; set; } } See image The Item and SubItem classes are
  • Fluent NHibernate中的NHibernate L2缓存配置(NHibernate L2 Cache configuration in Fluent NHibernate)
    问题 是否可以通过FHN在代码中配置L2缓存提供程序? 我需要在以下配置中添加一行: return Fluently.Configure() .Database(MsSqlConfiguration.MsSql2005.ConnectionString(c => c.FromConnectionStringWithKey("Temp")).ShowSql()) .Mappings(m => m.FluentMappings.AddFromAssemblyOf<IMap>()) .ExposeConfiguration(c => { }) .BuildSessionFactory(); 干杯 AWC 回答1 从FNH可以做到这一点,在下面的示例中,请参见'Cache'属性: return Fluently.Configure(fileConfiguration) .Database(MsSqlConfiguration .MsSql2005 .ConnectionString(c => c.FromConnectionStringWithKey("Temp")) .ShowSql() .Cache(c => c.ProviderClass(typeof(NHibernate.Cache.HashtableCacheProvider).AssemblyQualifiedName)
  • Fluent NHibernate和.NET 4的怪异替代问题(Weird override problem with Fluent NHibernate and .NET 4)
    问题 我最近问了一个关于在.NET 4中使用Fluent NHibernate的问题-我解决了这个问题,但是遇到了一个新问题。 概括我目前的主要问题是配置数据库。 我正在遵循本指南,但尝试改用SQL Server 2008 Express,因为这就是我将要使用的内容,因此也是我需要学习的内容。 失败的代码: public static ISessionFactory CreateSessionFactory() { return Fluently.Configure() .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("mssql"))) .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Program>()) .ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true)) .BuildSessionFactory(); } 当我尝试运行我的应用程序时,在最后一行( .BuildSessionFactory() )上出现以下异常: 重写成员时违反了继承安全规则:“ FluentNHibernate.Cfg
  • 如何使用流利的NHibernate将枚举映射为int值?(How do you map an enum as an int value with fluent NHibernate?)
    问题 问题确实如此,默认是将其映射为string但我需要将其映射为int 。 我目前正在使用PersistenceModel来设置我的约定,如果有什么不同的话。 提前致谢。 更新发现从主干上获取最新版本的代码解决了我的麻烦。 回答1 定义此约定的方式有时是在以前更改的,现在是: public class EnumConvention : IUserTypeConvention { public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria) { criteria.Expect(x => x.Property.PropertyType.IsEnum); } public void Apply(IPropertyInstance target) { target.CustomType(target.Property.PropertyType); } } 回答2 因此,如上所述,从后备箱中获取最新版本的Fluent NHibernate将我带到了我需要的地方。 具有最新代码的枚举的映射示例为: Map(quote => quote.Status).CustomTypeIs(typeof(QuoteStatus)); 自定义类型强制将其作为枚举的实例进行处理,而不是使用GenericEnumMapper<TEnum
  • Syntax to define a NHibernate Filter with Fluent Nhibernate?
    It seems I can't find the correct syntax to define a nhibernate filter using fluent Nhibernate. I'm trying to follow this ayende's blogpost: http://ayende.com/Blog/archive/2006/12/26/LocalizingNHibernateContextualParameters.aspx I defined the formula on my property with .FormulaIs() method but can't find on google how to translate this definition to fluent nhibernate: < filter-def name='CultureFilter'> < filter-param name='CultureId' type='System.Int32'/> < /filter-def>
  • Mapping enum with fluent nhibernate
    I am following the http://wiki.fluentnhibernate.org/Getting_started tutorial to create my first NHibernate project with Fluent NHibernate I have 2 tables 1) Account with fields Id AccountHolderName AccountTypeId 2) AccountType with fields Id AccountTypeName Right now the account types can be Savings or Current So the table AccountTypes stores 2 rows 1 - Savings 2 - Current For AccoutType table I have defined enum public enum AccountType { Savings=1, Current=2 } For Account table I define the entity class public class Account { public virtual int Id {get; private set;} public virtual string
  • ASP.NET MVC 1 and 2 on Mono 2.4 with Fluent NHibernate
    I'd like to create an application using ASP.NET MVC, that should run under mono 2.4 (compiling will be done on a Windows box). Has anyone getting luck with this? Here is what I've already tried: ASP.NET MVC on mono without any persistence model support, and using nhaml as the view engine S#aml architecture, which is a quite good framework imho, but it depends too much on stuff, that are not working good under mono (like windsor) The first part worked fine, I didn't encounter any major problems. But I couldn't get the second part working. It seems it's dependency on Castle.Windsor breaks the
  • Fluent NHibernate, working with interfaces
    I just switched to Fluent NHibernate and I've encountered an issue and did not find any information about it. Here's the case : public class Field : DomainObject, IField { public Field() { } public virtual string Name { get; set; } public virtual string ContactPerson { get; set; } public virtual bool Private { get; set; } public virtual IAddress Address { get; set; } } IAddress is an interface implemented by a class named Address public class Address : DomainObject, IAddress { public Address() { } public virtual string City { get; set; } public virtual string Country { get; set; } public
  • 用流利的hibernate映射枚举(Mapping enum with fluent nhibernate)
    问题 我正在按照http://wiki.fluentnhibernate.org/Getting_started教程使用Fluent NHibernate创建我的第一个NHibernate项目。 我有2张桌子 1)带有字段的帐户 Id AccountHolderName AccountTypeId 2)带字段的AccountType Id AccountTypeName 现在,帐户类型可以是Savings或Current,因此表AccountTypes存储2行1-Savings 2-Current 对于AccoutType表,我已经定义了枚举 public enum AccountType { Savings=1, Current=2 } 对于“帐户”表,我定义实体类 public class Account { public virtual int Id {get; private set;} public virtual string AccountHolderName {get; set;} public virtual string AccountType {get; set;} } 流利的nhibernate映射为: public AgencyMap() { Id(o => o.Id); Map(o => o.AccountHolderName); Map(o => o