NHibernate, SQL Server - mapping an enum to int

I have a class that has an enumeration type indicating whether the message type is Email or Sms. The type of listing is defined:

public enum ReminderType { Email = 1, Sms = 2 } 

The class that uses this type is as follows:

 public class Reminder : EntityBase { public virtual string Origin { get; set; } public virtual string Recipient { get; set; } public virtual ReminderType Type { get; set; } public virtual Business Business { get; set; } public virtual DateTime Created { get; set; } public Reminder() { Created = DateTime.UtcNow; } } 

When I try to save an entity of type Reminder in the database, I get the following error:

 System.Data.SqlClient.SqlException (0x80131904): Conversion failed when converting the nvarchar value 'Email' to data type int. 

The backing field is of type int , so I'm not sure why NHibernate is trying to match the default string representation. I am using Fluent NHibernate, and the corresponding mapping code:

 mappings.Override<Reminder>(map => { map.Map(x => x.Type).Column("Type") }); 

I am sure that the default behavior of NHibernate is to display enums as ints, so why is this not the case in this case? I am using SQL Server 2005 if that matters.

+6
source share
3 answers

I don’t know why this person continues to post and then removes their comment or answer, but the link they provided () answers my question. I decided not to go with a full definition of the hit class for the convention, but rather is a built-in convention in the mapping code, for example:

 var mappings = AutoMap.AssemblyOf<Business>() .Where(x => x.IsSubclassOf(typeof(EntityBase))) .IgnoreBase(typeof(EntityBase)) .Conventions.Add ( ConventionBuilder.Id.Always(x => x.GeneratedBy.Identity()), ConventionBuilder.HasMany.Always(x => x.Cascade.All()), ConventionBuilder.Property.Always(x => x.Column(x.Property.Name)), Table.Is(o => Inflector.Pluralize(o.EntityType.Name)), PrimaryKey.Name.Is(o => "Id"), ForeignKey.EndsWith("Id"), DefaultLazy.Always(), DefaultCascade.All(), ConventionBuilder.Property.When( c => c.Expect(x => x.Property.PropertyType.IsEnum), x => x.CustomType(x.Property.PropertyType)) ); 

The last congressional builder instruction did the trick. I'm curious why Fluent NHibernate's default is to now display enums as strings. That doesn't seem to make much sense.

+3
source

I do the same and do it this way ...

In my case, EmployeeType is an enumeration class.

  Map(x => x.EmployeeType, "EmployeeType_Id").CustomType(typeof (EmployeeType)); 
+5
source

You should not match Enum as int in NHibernate. This causes the ghosts to update.

The best way is to simply not set the type property in the XML mappings. To achieve this in Fluent NHibernate, you can use .CustomType(string.Empty) .

You can find some additional information here .

0
source

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


All Articles