Cole W
Cole W

Reputation: 15313

Mapping an int Enum to Numeric(9, 0) or Number(9, 0)

I have a mapping that I'm not quite sure how to do. I have a table that has a Numeric(9,0) column with possible values of 0-3. I'd like to represent this as an enumeration within my entity but there isn't a direct mapping of a Numeric(9, 0) to an integer. The reason it's numeric is for cross-database support (MSSQL and Oracle).

Numeric(9,0) maps directly to a C# decimal which cannot be an enumeration. This is not one of the allowed types for an enumeration.

Would I need to leverage an IUserType in conjuction with an ITypeConvention here or is there another way? Also given the following mapping (LoginType is the type in question) how would I implement this IUserType?

public enum LoginType : int
{
    UNKNOWN = 0,
    COMPANY_LOGIN = 1,
    WINDOWS_LOGIN = 2,
    LDAP_LOGIN = 3
}

public class UserHeader
{
    public virtual Guid UserId { get; set; }
    public virtual LoginType LoginType { get; set; }
}

Upvotes: 0

Views: 476

Answers (1)

KeithS
KeithS

Reputation: 71591

Try using the CustomType and CustomSqlType specifiers:

public class UserHeaderMap:ClassMap<UserHeader>
{
   public UserHeaderMap()
   {
      ...
      Map(x=>x.LoginType).CustomType(typeof(LoginType)).CustomSqlType("Numeric(9,0)");
   }
}

Specifying the custom type of the enumeration tells FNH to persist the numeric value, instead of its default behavior of persisting the ToString() value (and/or expecting it in the table). The CustomSqlType is more for schema generation purposes, overriding the default int type for the schema column.

If that doesn't work, try adding a Formula() instead of a CustomSqlType, to cast or convert the numeric to an int, which will be picked up by NH and cast to the enum value.

Upvotes: 1

Related Questions