天道酬勤,学无止境

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> 

评论

This recent post in the Fluent NHibernate discussion leads me to believe that filters are not yet supported by the Fluent API.

If you build Fluent from source, there is now support for filters. You use them like this:

First create a class inheriting from FluentNHibernate.Mapping.FilterDefinition:

using FluentNHibernate.Mapping;

namespace PonyApp.FluentFilters
{
    public class PonyConditionFilter : FilterDefinition
    {
        public PonyConditionFilter()
        {
            WithName("PonyConditionFilter")
                .AddParameter("condition",NHibernate.NHibernateUtil.String);
        }
    }
}

In your ClassMap for your class, use the ApplyFilter method:

namespace PonyApp.Entities.Mappings
{
    public class PonyMap : ClassMap<Pony>
    {
        public PonyMap()
        {
            Id(x => x.Id);
            Map(x => x.PonyName);
            Map(x => x.PonyColor);
            Map(x => x.PonyCondition);
            ApplyFilter<PonyConditionFilter>("PonyCondition = :condition");
        }
    }
}

Then add the filter to your fluent config:

Fluently.Configure()
    .Mappings(m => m.FluentMappings.Add(typeof(PonyConditionFilter)))
    //blah blah bunches of other important stuff left out
    .BuildSessionFactory();

Then you can turn it on and off just as you would with vanilla NHibernate:

session.EnableFilter("PonyConditionFilter").SetParameter("condition","Wonderful");

In case anyone's still watching this, I've just submitted a patch on Google code for Fluent NHibernate to support filters. You can see it in use in snicker's answer above.

受限制的 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>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • 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, 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
  • How to tell Fluent NHibernate not to map a class property
    I have a class that is mapped in fluent nhibernate but I want one of the classes properties to be ignored by the mapping. With class and mapping below I get this error: The following types may not be used as proxies: iMasterengine.Data.Model.Calendar: method get_HasEvents should be virtual //my class public class Calendar : IEntity { public virtual int Id { get; private set; } public virtual string Name { get; set; } public virtual string SiteId { get; set; } public virtual IList<CalendarEvent> Events { get; set; } //ignore this property public bool HasEvents { get { return Events.Count > 0; }
  • How do you map an enum as an int value with fluent NHibernate?
    Question says it all really, the default is for it to map as a string but I need it to map as an int. I'm currently using PersistenceModel for setting my conventions if that makes any difference. Thanks in advance. Update Found that getting onto the latest version of the code from the trunk resolved my woes.
  • Generate XML mappings from fluent Nhibernate
    How do I generate xml mappings files as part of my tests in MappingIntegrationTests I need to manually check if the fluent mappings correlate to the mappings in the leagcy project.
  • Unable to cast object of type NHibernate.Collection.Generic.PersistentGenericBag to List
    I have a class called ReportRequest as: public class ReportRequest { Int32 templateId; List<Int32> entityIds; public virtual Int32? Id { get; set; } public virtual Int32 TemplateId { get { return templateId; } set { templateId = value; } } public virtual List<Int32> EntityIds { get { return entityIds; } set { entityIds = value; } } public ReportRequest(int templateId, List<Int32> entityIds) { this.TemplateId = templateId; this.EntityIds = entityIds; } } It is mapped using Fluent Hibernate as: public class ReportRequestMap : ClassMap<ReportRequest> { public ReportRequestMap() { Id(x => x.Id)
  • Binary Blob truncated to 8000 bytes - SQL Server 2008 / varbinary(max)
    I have upgraded from Fluent Nhibernate 1.0 with Nhibernate 2.1 to pre- release 1.x with NHibernate 3.0 GA and have hit what I think is a regression, but I want to hear if that's indeed the case. I am using SQL Server Express 2008 and the MSSQL 2008 dialect and have an Image property of type System.Drawing.Image and I have mapped it like this: Map (food => food.Image) .Length (int.MaxValue) .Nullable (); The Image column in the table is of type varbinary(MAX). The generated hbm for the property is: <property name="Image" type="System.Drawing.Image, System.Drawing, Version=2.0.0.0, Culture
  • Circular reference causing stack overflow with Automapper
    I'm using Automapper to map my NHibernate proxy objects (DTO) to my CSLA business objects I'm using Fluent NHibernate to create the mappings - this is working fine The problem I have is that the Order has a collection of OrderLines and each of these has a reference to Order. public class OrderMapping : ClassMap<OrderDTO> { public OrderMapping() { // Standard properties Id(x => x.OrderId); Map(x => x.OrderDate); Map(x => x.Address); HasMany<OrderLineDTO>(x => x.OrderLines).KeyColumn("OrderId").Inverse(); Table("`Order`"); } } public class OrderDTO { // Standard properties public virtual int
  • IndexOutOfRangeException Deep in the bowels of NHibernate
    I have the following mappings: public class SecurityMap : ClassMap<Security> { public SecurityMap() { Table("Security"); CompositeId().KeyProperty(k => k.Id, "SecurityId").KeyProperty(k => k.EndDate); Map(x => x.LastUpdateUser); References(x => x.Company).Columns("CompanyId", "EndDate"); References(x => x.PrimaryListing).Columns("PrimaryListingId", "EndDate"); } } public class ListingMap : ClassMap<Listing> { public ListingMap() { Table("Listing"); CompositeId().KeyProperty(k => k.Id, "ListingID").KeyProperty(k => k.EndDate); References(x => x.Security).Columns("SecurityId","EndDate"); } }
  • How to save a child with assigned id in nhibernate
    I have two classes: public class Parent { public virtual long? ID { get; set; } // native public virtual IList<Child> Children { get; set; } public virtual string Name { get; set; } } public class Child { public virtual long ID { get; set; } // assigned public virtual string Name { get; set; } } Instantiating and saving parent and child: child = new Child() { ID = 1, Name = "SomeName" }; parent = new Parent() { Children = new List() { child } }; session.Save(parent); Which gives me: NHibernate.StaleStateException: Unexpected row count: 0; expected: 1. I think the problem is with the assigned
  • Entity Framework 4 vs NHibernate [closed]
    Closed. This question is opinion-based. It is not currently accepting answers. Want to improve this question? Update the question so it can be answered with facts and citations by editing this post. Closed 6 years ago. Improve this question A lot has been talked about Entity Framework first version on the web (also on stackoverflow) and it is clear that it was not a good choice when we already have better alternative like NHibernate. But I can't find a good comparison of Entity Framework 4 and NHibernate. We can say that today NHibernate is the leader among all .NET ORMs, but can we expect
  • NHibernate AliasToBean转换器关联(NHibernate AliasToBean transformer associations)
    问题 我正在尝试使用以下语句来获取具有我所关注的字段的实体: retVal = session.CreateCriteria(typeof(MyEntity)) .CreateAlias("MyEntityProperty", "MyEntityProperty") .Add(Restrictions.Eq("MyEntityProperty.Year", year)) .SetProjection( Projections.Distinct( Projections.ProjectionList() .Add(Projections.Property("Property1"), "Property1") .Add(Projections.Property("Property2"), "Property2") .Add(Projections.Property("MyEntityProperty.RegisteredUser"), "MyEntityProperty.RegisteredUser") .Add(Projections.Property("MyEntityProperty.CompanyInfo"), "MyEntityProperty.CompanyInfo") ) ) .SetResultTransformer(Transformers.AliasToBean
  • Nhibernate:如何用一对多关系表示多对多关系?(Nhibernate: How to represent Many-To-Many relationships with One-to-Many relationships?)
    问题 我已经在互联网上阅读了一篇帖子(我再也找不到该帖子供我参考),可以将一对多关系替换为一对多关系。 有人可以提供例子吗? 回答1 我只是提出这个问题,并意识到,缺少任何答案。 很遗憾,尽管我经常指出NHibernate文档声明:24.最佳实践 不要使用奇异的关联映射。 真正的多对多关联的好用例很少。 大多数时候,您需要存储在“链接表”中的其他信息。 在这种情况下,对中间链接类使用两个一对多关联会更好。 实际上,我们认为大多数关联是一对多和多对一的,在使用任何其他关联样式时,请务必小心,并问问自己是否真的必要。 看一下23.2下的示例。 作者/作品。 摘录, Author与Work之间多对多关系的简化版本: <class name="Work" table="works" ...> <id name="Id" column="id" generator="native" /> ... <set name="Authors" table="author_work" lazy="true"> <key> <column name="work_id" not-null="true"/> </key> <many-to-many class="Author"> <column name="author_id" not-null="true"/> </many-to-many> </set
  • Minimal and correct way to map one-to-many with NHibernate
    I am new to NHibernate and C#, so please be gentle! I have the following two NHibernate entities: Employee { private long _id; private String _name; private String _empNumber; private IList<Address> _addresses; //Properties... } and Address { private long _id; private String _addrLine1; private String _addrLine2; private String _city; private String _country; private String _postalCode; //Properties } and they have a one-to-many relationship from Employee to Address (each employee can have multiple addresses in their record). Conveniently ignoring the fact that more than one employee may
  • NHibernate - Many to Many Query using Junction/Joiner Table
    I've found very similar questions here but none that match exactly what I'm looking for. The two closest threads I've found are (yes, they are different threads): NHibernate many-to-many criteria (1) NHibernate many-to-many criteria (2) However, I think both of those are using direct Many-to-Many relationships. I am actually simulating the Many-to-Many relationship by having two One-to-Many relationships with a junction table, which is pretty standard practice. Here are my NHibernate mappings: Files: <class name="Files" table="files"> <id name="id"> <generator class="identity" /> </id>
  • NHibernate configuration for uni-directional one-to-many relation
    I'm trying to set up a relationship as follows. Each Master item has one or more Detail items: public class Detail { public virtual Guid DetailId { get; set; } public virtual string Name { get; set; } } public class Master { public virtual Guid MasterId { get; set; } public virtual string Name { get; set; } public virtual IList<Detail> Details { get; set; } } And Mappings: public class MasterMap : ClassMap<Master> { public MasterMap() { Id(x => x.MasterId); Map(x => x.Name); HasMany(x => x.Details).Not.KeyNullable.Cascade.All(); } } public class DetailMap : ClassMap<Detail> { public DetailMap(
  • NHibernate ISession Flush:何时何地使用它,为什么?(NHibernate ISession Flush: Where and when to use it, and why?)
    问题 使我彻底困惑的一件事是使用session.Flush以及session.Commit和session.Close 。 有时session.Close可以工作,例如,它会提交我需要的所有更改。 我知道我在有事务或具有多个创建/更新/删除的工作单元时需要使用提交,以便在发生错误时可以选择回滚。 但是有时候我确实被session.Flush背后的逻辑所session.Flush 。 我看过一些示例,其中有一个session.SaveOrUpdate()然后进行刷新,但是当我删除Flush时,它仍然可以正常工作。 有时,我在Flush语句上遇到错误,说会话超时,将其删除会确保我没有遇到该错误。 是否有人在哪里或何时使用同花顺有良好的指导原则? 我已经检查了NHibernate文档,但是仍然找不到简单的答案。 回答1 简要地: 一律使用交易不要使用Close() ,而是将您的调用包装在using语句内的ISession上,或者在其他地方管理ISession的生命周期。 从文档中: ISession有时会执行将ADO.NET连接状态与内存中保存的对象状态同步所需的SQL语句。 默认情况下,此过程在以下几点进行刷新从Find()或Enumerable()一些调用中来自NHibernate.ITransaction.Commit() 从ISession.Flush()
  • How to partially project a child object with many fields in nHibernate
    I have the following nHibernate query that select a course based on its course id and then return selected fields for the course object on the initial fetch, and the query executes with no issues. MatchMode option = ... CourseItem courseAlias = null; TeacherItem teacherAlias = null; var query = session.QueryOver<CourseItem>() .JoinAlias(c => c.Teacher, () => teacherAlias) .Where(c => c.CourseID.IsInsensitiveLike(strNumber, option)) .SelectList(list => list .Select(c => c.CourseID).WithAlias(() => courseAlias.CourseID) .Select(c => c.IsActive).WithAlias(() => courseAlias.IsActive) .Select(c =>
  • What exactly is “persistence ignorance”?
    Persistence ignorance is typically defined as the ability to persist & retrieve standard .NET objects (or POCOs if you really insist on giving them a name). And a seemingly well accepted definition of a standard .NET object is: "...ordinary classes where you focus on the business problem at hand without adding stuff for infrastructure-related reasons..." However, I see people describing NHibernate as a framework that allows persistence ignorance, and yet it is a framework that cannot work on any standard .NET object, only standard .NET objects that adhere to particular design requirements, for
  • When to use inverse=false on NHibernate / Hibernate OneToMany relationships?
    I have been trying to get to grips with Hibernate's inverse attribute, and it seems to be just one of those things that is conceptually difficult. The gist that I get is that when you have a parent entity (e.g. Parent) that has a collection of Child objects using a one-to-many mapping, setting inverse=true on the mapping tells Hibernate that 'the other side (the Child) has responsibility to update itself to maintain the foreign key reference in its table'. Doing this appears to have 2 benefits when it comes to adding Children to the collection in your code, and then saving the Parent (with