2

Is there an easy way to automatically truncate strings using fluent nHibernate mappings. I would prefer to not address this the setters or a custom type, but with something in the mapping files.

0

1 Answer 1

1

If I understand you correctly you want to make sure strings persisted to the database are no longer than a specified length. This sounds like it could be a business concern though and probably does belong in the domain model or as validation logic.

This question appears to have been asked before and the solution was a custom nHibernate UserType. Keep in mind this isn't a custom entity type or base class, this is a custom mapping type that nHibernate can understand. Automatically truncating strings in NHibernate / SQL Server

If the custom usertype solution isn't to your liking then you could implement a custom interceptor, but I don't believe there is anything in nHibernate that does this "out-of-the-box". However, that is the beauty of nHibernate is that it is very extensible and implementing a custom user type for your situation is not difficult at all.

3
  • my thoughts on the matter is that a custom mapping type is alot of work for every string that has a different length. I also think that my db field length restrictions shouldn't end up in my domain model, although that is the current solution. I haven't looked at the custom interceptor, but I guess it is going to require customization for every mapped field. I did see the above post, and I didn't like the solution. I also saw another post from 2007 here: forums.hibernate.org/… that lead me to believe this is possible.
    – Rob Allen
    Commented Dec 30, 2009 at 23:13
  • You shouldn't have to have a type for every length, you just set the string length property in the mapping. If you are trying to avoid setting the string length in the mapping I think you may be out of luck, I don't think nHibernate has any way to know what the SQL string length settings are. Commented Jan 8, 2010 at 0:33
  • One other option would be using a custom nHibernate validator attribute on your model properties as another way to do this something like: [Truncate(length = 25)] public string StringProperty { get; set;} Even without nHibernate validators the attribute could be used with a very simple nHibernate interceptor. If you want an example of that let me know. Commented Jan 8, 2010 at 0:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.