Using Enums as a lookup
Assuming I have the following class:-
public class ErrMessage
{
public virtual int Id {get; set;}
public MyWarningLevel Level {get; set;}
public string Message {get; set;}
} public enum MyWarningLevel
{
Info,
Warning,
Error,
}
In SQL the tables are already created as:-
CREATE TABLE [dbo].[ErrMessage]
(
[LevelId] [int] IDENTITY(1,1) NOT NULL,
[LevelName] [varchar](50) NOT NULL,
)
ALTER TABLE [dbo].[ErrMessage] WITH CHECK ADD CONSTRAINT [FK_ErrMessage_WarningLevel_ID] FOREIGN KEY([LevelId])
REFERENCES [dbo].[WarningLevel] ([LevelId])
ALTER TABLE [dbo].[ErrMessage] CHECK CONSTRAINT [FK_ErrMessage_WarningLevel_ID]
CREATE TABLE [dbo].[WarningLevel]
(
[LevelId] [int] IDENTITY(1,1) NOT NULL,
[LevelName] [varchar](50) NOT NULL,
)
So my question is how can I create a mapping for the ErrMessage class that uses the string name of the enum to find the LevelId from the database. The ID's will not match the enum cast to an int so i need it to look up the id.
2 Posted by Richard Gavel on 21 Jul, 2010 07:58 PM
What you're missing is a way to convert the enum value into a ID to use when persisting an instance ErrMessage. What you need is a class that implements IUserType, which is a class that converts between the POCO representation of a property to the database representation of a property. Check out the Hibernate YesNoType class, which is used to map Yes/No to True/False in the DB. In your ClassMap file, you would just use the UserType method to link the implementation class to the property to use it with.