Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map enum as string in database

My table:

create table MyTable (
    Id int identity(1,1) not null,
    MyStatus char(2) not null
)
insert into MyTable(MyStatus) select 'A'

Class and enum:

public class MyTable
{
    public virtual int Id { get; set; }
    public virtual MyTableStatus MyStatus { get; set; }
}

public enum MyTableStatus
{
    A,
    B
}

Mapping:

public MyTableMap()
{
    Id(x => x.Id);
    Map(x => x.MyStatus);
}

When I execute the following test, I get System.FormatException : Input string was not in a correct format...

[Test]
public void Blah()
{
    MyTable myTable = Session.Get<MyTable>(1);
    Assert.That(myTable.MyStatus, Is.EqualTo(MyTableStatus.A));
}

What is the right way to map an enum to it's string representation in the database?

Edit - I am writing my application on an existing database, which I cannot modify easily because it is used by other applications also. So some fields in the database (which I would like to represent as enums in my application) are of type int and some of type char(2).

like image 982
sventevit Avatar asked Jan 09 '11 00:01

sventevit


People also ask

Can we use enum as string?

Since Enum in Java allows a programmer to override an inherited method and since Enum has access to all Object class methods, you can easily override the toString() method to provide a custom String implementation for an Enum instance which can further use to convert that Enum instance to String in Java.

Can enum store string?

Enum constants can only be of ordinal types ( int by default), so you can't have string constants in enums.


1 Answers

You need to create a custom IUserType to convert an enum to its string representation and back. There's a good example in C# here and an example in VB.NET for working with enums here (scroll down to implementing IUserType).

like image 121
Jamie Ide Avatar answered Oct 09 '22 12:10

Jamie Ide