NHibernate enumeration collection mapping

I try to map a collection of enumerations to NHibernate using Fluent NHibernate, and then query against the contents of this collection of enumerations, but the system throws exceptions every time.

I have a Widget class mapped to a Widget table. There is also a WidgetType enumeration, and a single Widget instance can have many WidgetTypes types displayed through the WidgetTypes property. The property must be mapped to a separate WidgetTypeRef table with two integer columns: WidgetId and WidgetType.

public class Widget
{
  /* omitted */
  public IList<WidgetType> WidgetTypes { get; set; }
}
public enum WidgetType
{
  SomeType = 0,
  SomeOtherType = 1,
  YetOneMoreType = 2
}
public partial class WidgetMapping : IAutoMappingOverride<Widget>
{
  public void Override(AutoMapping<Widget> mapping)
  {
    /* omitted */
    mapping.HasMany(w => w.WidgetTypes)
      .Table("WidgetTypeRef")
      .KeyColumn("WidgetId")
      .Element("WidgetType");
  }
}

; . WidgetType, , . Ref.

, ".CustomType(typeof (someTypeEnum)", CustomType HasMany. HasMany , " .

? ? Fluent? ( Any Contains)?

+3
1
public class EnumToIntConvention : IUserTypeConvention
{
    public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
    {
        criteria.Expect(x => x.Property.PropertyType.IsEnum);
    }

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

, Enum:

public enum Status
{
    Inactive = 0,
    Active = 1,
    Canceled = 2
}

( Fluent-):

var cfg = Fluently.Configure()
    .Database(configurer)
    .Mappings(m =>
    {
        m.AutoMappings.Add(AutoMap.Assemblies(Assembly.GetExecutingAssembly())
            .Where(type => AutomapAssemblies.Contains(type.Namespace))
            .Conventions.Add<EnumToIntConvention>()  // Magic code goes here!
            .Conventions.Add());
    });

integer string.

+2

Source: https://habr.com/ru/post/1766821/


All Articles