天道酬勤,学无止境

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, PublicKeyToken=null]], FluentNHibernate, Version=1.1.0.0, Culture=neutral, PublicKeyToken=8aa435e3cb308880">
  <column name="ComponentTypeId" />
</property>

It doesn't seem right that it would be using a GenericEnumMapper when an IUserTypeConvention is specified for enums.

Here is my convention:

public class EnumConvention : IUserTypeConvention
{
    public void Accept( IAcceptanceCriteria<IPropertyInspector> criteria )
    {
        criteria.Expect( e => e.Property.PropertyType.IsEnum );
    }

    public void Apply( IPropertyInstance instance )
    {
        instance.CustomType( instance.Property.PropertyType );
    }
}

评论

Simply doing Map( m => m.MyEnum ).CustomType<MyEnum>() seems to work just fine now.

If anyone knows why IUserTypeConvention doesn't work with Fluent NHibernate in NHibernate 3, I'd still like to know why. Maybe it's because mapping the custom type to the enum works now, but why wasn't it removed from the lib then?

I'm running into a similar problem with Nhibernate 3.0GA and FluentNh (rebuild with the latest NH version). UserTypeConventions are not getting registered properly.

problem described here : http://groups.google.com/group/nhusers/browse_thread/thread/c48da661f78bfad0

You should inherit your convention not from IUserTypeConvention, but from FluentNHibernate.Conventions.UserTypeConvention.

For example, this is the exact convention I use to map boolean and nullable booleans to a custom type called UserTrueFalseType:

    /// <summary>
/// Convention: Boolean fields map to CHAR(1) T/F/Null
/// </summary>
public class BooleanTrueFalseConvention : FluentNHibernate.Conventions.UserTypeConvention<UserTrueFalseType>
{
    /// <summary>
    /// Accept field type criteria
    /// </summary>
    /// <param name="criteria"></param>
    public override void Accept(FluentNHibernate.Conventions.AcceptanceCriteria.IAcceptanceCriteria<FluentNHibernate.Conventions.Inspections.IPropertyInspector> criteria)
    {
        criteria.Expect(instance =>
            instance.Property.PropertyType.Equals(typeof(System.Boolean))
            ||
            instance.Property.PropertyType.Equals(typeof(System.Nullable<System.Boolean>))
        );
    }
}

This works with NH 3.3 and the last version of Fluent.

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

相关推荐
  • 如何使用流利的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
  • 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.
  • 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
  • How do you map an enum as string in fluent nhibernate?
    Is it possible to map an enum as a string using 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
  • 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
  • 如何在流利的NHibernate中加入表(How to join table in fluent nhibernate)
    问题 我们如何做到这种映射却又流利呢? <class name="Person" table="People"> <id name="Id"> <generator class="identity"/> </id> <property name="Name" /> <join table="Addresses"> <key column="PersonId"/> <property name="Line1"/> <property name="Line2"/> <property name="City"/> <property name="Country"/> <property name="ZipCode"/> </join> </class> 我知道我可以使用“参考”,但是我不需要相关表中的所有列。 我只需要一个财产。 回答1 帕科说的话不对。 这可以在Fluent NHibernate中完成。 我自己上网搜索了很长时间,找不到任何人在谈论这个选项,所以我只是和FNHibernate玩了一会儿,最后设法做到了。 这是我的情况: 我有两个桌子- "FormFields" => Columns { "FieldId", "FieldName", "FieldType", "DisplayOrder" } "FormStructure" => Columns { "FormId",
  • 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; }
  • DateTime precision in NHibernate and support for DateTime2 in NHibernate SchemeExport
    I am then using Fluent NHibernate and its automapping feature to map the the following simplified POCO class: public class Foo { public virtual int Id { get; set; } public virtual datetime CreatedDateTime { get; set; } } The CreatedDateTime field will map to a SQL DateTime by default. However if I do a test to check that the entity is being created correctly it fails. This is because the precision of the DateTime field is not maintained through to the SQL database. I undersatnd the reason behind this to be that a MS SQL Server DateTime can only hold milisecond precision by rounded to
  • NHibernate.Spatial and Sql 2008 Geography type - How to configure
    I am trying to use Nhibernate with the Sql 2008 Geography type and am having difficulty. I am using Fluent Nhibernate to configure which I am fairly new to so that may be the problem as well. First, the class I am trying to persist looks something like: public class LocationLog : FluentNHibernate.Data.Entity { public virtual new int Id {get;set;} public virtual DateTime TimeStamp {get;set;} public virtual GisSharpBlog.NetTopologySuite.Geometries.Point Location {get;set;} } The mapping class looks like: public class LocationLogMap : ClassMap<LocationLog> { ImportType<GisSharpBlog
  • 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
  • 流利的NHibernate HasManyToMany()映射(Fluent NHibernate HasManyToMany() Mapping)
    问题 我在使用多对多关系的Fluent NHibernate示例中遇到问题。 我试图找出类似案例的例子,但发现了很多吨,但我仍然遇到同样的问题。 运行测试项目时,将引发以下异常: NHibernate.PropertyAccessException:项目.Entities.User.UserName的吸气剂发生异常---> System.Reflection.TargetException:对象与目标类型不匹配。 这是表的图像: 和代码 public UsersMap() { this.Table("Users"); Id(x => x.UserName).Column("Username").GeneratedBy.Assigned(); Map(x => x.FirstName); Map(x => x.LastName); Map(x => x.Password); Map(x =>x.EMail); Map(x => x.Title); Map(x => x.Division); HasManyToMany<User>(x => x.Roles) .Table("UserInRoles").ParentKeyColumn("Username") .ChildKeyColumn("Usernamepk") .Cascade.SaveUpdate().LazyLoad(); }
  • Fluent NHibernate Column Mapping with Reserved Word
    I've read that using a back tick ` should allow for using of reserved words. I'm using SQL Server and Fluent NHibernate and have a column name "File". If I map it with "`File" it tries using [Fil] so it's adding the brackets correctly, but dropping the "e" from the end. If I map it as "`Filee" it uses [File] correctly. Am I doing something wrong or is this a bug in NHibernate or Fluent Nhibernate?
  • Fluent NHibernate HasManyToMany() Mapping
    I am having a problem in Fluent NHibernate example utilizing the Many-to-Many relationships. I tried to find out examples on a similar case, and I found tons, but I'm still having the same problem. When running the test project, the following exception is thrown: NHibernate.PropertyAccessException: Exception occurred getter of project.Entities.User.UserName ---> System.Reflection.TargetException: Object does not match target type. This is an image of the tables: and the code public UsersMap() { this.Table("Users"); Id(x => x.UserName).Column("Username").GeneratedBy.Assigned(); Map(x => x
  • How to map IDictionary<string, Entity> in Fluent NHibernate
    I have an class with an IDictionary on it. <map name="CodedExamples" table="tOwnedCodedExample"> <key> <column name="OwnerClassID"/> </key> <index type="string" column="ExampleCode"/> <many-to-many class="CodedExample" column ="CodedExampleClassID"/> </map> as you can see it uses a many-to-many to get the CodedExamples from their table using the tOwnedCodedExample table to find which are owned by the OwnerClass. I realise that this is a very basic (and hopefully standard) mapping but am struggling and can't find any documentation for it, therefore would be very grateful of any help possible
  • Fluent NHibernate - Map 2 tables to one class
    I have a table structure something like this table Employees EmployeeID EmployeeLogin EmployeeCustID table Customers CustomerID CustomerName What i would like is to map the structure above to one single class named: Class Employee EmployeeID EmployeeLogin EmployeeName How do i do that with fluent nhibernate ?
  • How do you automap List<float> or float[] with Fluent NHibernate?
    Having successfully gotten a sample program working, I'm now starting to do Real Work with Fluent NHibernate - trying to use Automapping on my project's class heirarchy. It's a scientific instrumentation application, and the classes I'm mapping have several properties that are arrays of floats e.g. private float[] _rawY; public virtual float[] RawY { get { return _rawY; } set { _rawY = value; } } These arrays can contain a maximum of 500 values. I didn't expect Automapping to work on arrays, but tried it anyway, with some success at first. Each array was auto mapped to a BLOB (using SQLite)
  • 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
  • 亚音速VS NHibernate [关闭](Subsonic Vs NHibernate [closed])
    问题 关门了。 这个问题是基于意见的。 它当前不接受答案。 想要改善这个问题吗? 更新问题,以便可以通过编辑此帖子以事实和引用的形式回答。 3个月前关闭。 改善这个问题 什么时候使用这些工具中的一个不利于另一个工具的共识是什么? 我发现Subsonic在快速完成工作方面非常有用,但是在大型项目中,它往往无法扩展,并且将您的域模型与数据库模型联系在一起。 这就是Nhibernate出现的地方,因为它为您提供了与数据库模型无关的轻量级POCO,但是建立时间更长。 回答1 我经常被问到这个问题,实际上归结为您想花多少钱。 我无法告诉您Chris Cyvas的评论RE SubSonic缩放的破坏性如何-自从:(。 这笔交易是-明智的选择,SubSonic的扩展性非常好。 就项目增长而言-您使用的任何工具都需要引起您的注意。 甚至NHibernate。 我写了一篇关于如何在SubSonic 2.1中将存储库模式用于DI(就像使用NHIb或其他工具一样)的文章: http://blog.wekeroad.com/blog/subsonic-writing-decoupled-testable-code-with-subsonic-2-1/ 我还写了一篇有关SubSOnic性能的文章: http://blog.wekeroad.com/blog/subsonic-scaling/ 希望这可以帮助