2011-03-21 41 views
23

我用這個How do you map an enum as an int value with fluent NHibernate?映射在過去,但我最近升級到NHibernate 3,這似乎並沒有工作了。我在EnumConvention類中放置了斷點,但它們沒有被擊中。正在訪問數據庫的查詢將枚舉作爲默認配置的字符串。使用流利NHibernate和NHibernate的地圖枚舉作爲Int

這對NHibernate 3是如何工作的?

更新

這裏是生成的映射文件的一部分:

<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> 

似乎不正確的,當枚舉指定了IUserTypeConvention它會使用GenericEnumMapper

這裏是我的約定:

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); 
    } 
} 
+0

我真的看不到你從這個練習中獲得什麼,但是這可能因爲某種原因被刪除了,因爲他們的力量發現需要保持它 – Baz1nga 2011-03-22 04:32:35

+0

我沒有看到它消失的任何地方,它只是似乎沒有工作了。那麼該怎麼辦呢?做'Map(...).CustomType ()'不起作用。它會導致問題。我會嘗試做一個自定義的IUserType,看看現在是否可行。 – 2011-03-22 14:31:05

+0

林說,你有任何理由將其存儲爲一個int而不是枚舉嗎?隨着mem nt一個概率我真的沒看到一個原因..字符串枚舉是代碼安全.. – Baz1nga 2011-03-22 20:00:09

回答

43

簡單地做Map(m => m.MyEnum).CustomType<MyEnum>()似乎現在的工作就好了。

如果有人知道爲什麼IUserTypeConvention不能在NHibernate 3中使用流利NHibernate,我仍然想知道爲什麼。也許這是因爲將自定義類型映射到枚舉現在可行,但爲什麼它不是從lib中刪除?

+0

簡單的解決方案...爲我節省了大量的時間調試! – 2011-06-28 16:35:57

+0

工作完美,謝謝! – vfilby 2012-10-12 02:37:36

+0

這個解決方案對我來說更好,它試圖定義一個約定。按照慣例,類型未按預期在SQL Server 2014表上設置。 – gopherr 2015-08-26 18:32:51

0

你應該繼承不IUserTypeConvention您的慣例,而是從FluentNHibernate.Conventions.UserTypeConvention。

例如,這是我使用布爾和可空布爾值映射到名爲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>)) 
     ); 
    } 
} 

這工作與NH 3.3和流利的最後一個版本。