views:

101

answers:

1

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.

A: 

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. http://stackoverflow.com/questions/831452/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.

Chris Nicola
Rob A
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.
Chris Nicola
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.
Chris Nicola