简体   繁体   中英

Nhibernate and enums

Is a good habit to use enums with databases (NHibernate + mysql)? What are the advantages and disadvantages? Does it have influence to database efficiency?

Is a good habit to use enums with databases (NHibernate + mysql)?

I think it definitely makes sense from a programmer's perspective to use enums where applicable. It makes for much more readable code and eliminates "invalid" values in your database.

What are the advantages and disadvantages? Does it have influence to database efficiency?

Advantages:

  1. Readability from the code
  2. Data integrity

Disadvantages:

  1. Overhead in conversions of enums to database types. Although this is probably negligible. Haven't tested this but I would assume this is the case.

I'm sure the rest of the community can definitely add to the list above but I would say overall using enums is a good idea where it makes sense.

I think from a code perspective, enums definitely make sense. However, if you are using NHibernate to generate your database schema, look out for it using MySQL's Enum Data Type . This will store your enums as strings, but enforce that only valid values are entered. This can be costly from a storage perspective, and also when trying to refactor. The enum database type will handle validation at the database level for you, so arbitrary updates will be less worrisome, I prefer storing the numeric value and relying on the application to validate, because it makes it easier to add or rename enum members.

I have no idea if this is the best approach or not (if you're using fluent nhibernate, this can almost certainly be accomplished using conventions) but if you look at this blog post you can find an IUserType that handles mapping enums as integers in MySQL and goes over some of the challenges encountered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM