Using NHibernate 3.2 mapping by code (not fluent-nhibernate), I'm trying to map an Enum field to a string column instead of the default int representation. I can't get the right syntax.
For example:
public class Account {
public enum StateType { Pending, Active, Cancelled, Suspended }
...
public virtual StateType State { get; set; }
...
}
In the XML mapping, you can use NHibernate.Type.EnumStringType
(see this link), but how do I do it in mapping by code?
NHibernate.Mapping.ByCode.ModelMapper mapper = new NHibernate.Mapping.ByCode.ModelMapper();
mapper.Class<Account>(map => {
map.Id(x => x.Id, attr => {
attr.Column("id");
attr.Generator(NHibernate.Mapping.ByCode.Generators.Identity);
});
// Default 'int' mapping
//map.Property(x => x.State);
// Cannot implicitly convert type 'StateType' to 'NHibernate.Type.EnumStringType'
//map.Property<NHibernate.Type.EnumStringType<Account.StateType>>(x => x.State);
Update:
Using this mapping, I managed to get it to save as a string to the DB, but I now get an exception when loading from the DB to the object model.
map.Property(x => x.State, attr => { attr.Type(NHibernateUtil.String); });
This is the exception I get when trying to load the object:
Invalid Cast (check your mapping for property type mismatches); setter of Model.Account
NHibernate is an object–relational mapping (ORM) solution for the Microsoft . NET platform. It provides a framework for mapping an object-oriented domain model to a traditional relational database.
Fluent NHibernate offers an alternative to NHibernate's standard XML mapping files. Rather than writing XML documents, you write mappings in strongly typed C# code. This allows for easy refactoring, improved readability and more concise code.
Got it! The following syntax works:
map.Property(x => x.State, attr => attr.Type<NHibernate.Type.EnumStringType<Account.StateType>>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With