1

In pursuit of finding the best way to have a date displayed on a Razor as just a short date, I have stumbled across Data Annotations, they seem quite nice being able to attach additional meta-data to my various models.

Here's the catch though: I'm using NHibernate configured by Fluent NHibernate, and NHibernate doesn't seem to carry the attributes over to it's generated proxy classes.

Is there some way to force it to copy the attributes, or should I not be using my model classes directly in a view, and instead transform the model someway (T4 template?)

Matt Sieker
  • 9,349
  • 2
  • 25
  • 43
  • The attributes should be part of your ViewModel, not the persistence model. – Phill Feb 06 '11 at 20:22
  • @Phil, I've figured that since I posted this, but I figured it would be worth getting a few other opinions. I'm looking at using AutoMapper to remove some of the drudgery. – Matt Sieker Feb 06 '11 at 20:25

2 Answers2

2

Are the NHibernate models you are using partial classes? If so, you can create a separate metadata class to decorate them with the data annotations. I recently had a similar problem and got this answer to my question here. Basically, you create a partial class of the same name as the NHibernate class that was generated. You then create a metadata class with the same fields as that class, decorate them appropriately, and then apply that metadata class to the partial class you created, so that even if you regenerate classes, your partial class won't, and will keep your DataAnnotations around.

[MetadataType(typeof(PersonMetadata))]
public partial class Person {

}

public class PersonMetadata {

   [Required]
   [Display(Name = "First Name")]
   public string FirstName;
}

Source: Austin Lamb via this answer.

Community
  • 1
  • 1
Ryan Hayes
  • 5,290
  • 4
  • 42
  • 52
  • Not sure whether your answer addresses the original question, but the meta data class could possibly be linked to both the domain and the view model. – Gerke Geurts Feb 08 '11 at 01:18
2

I would recommend you to separate classes for view and domain model (nhibernate). Use automapper to translate from one to another.

justSteve
  • 5,444
  • 19
  • 72
  • 137
gor
  • 11,498
  • 5
  • 36
  • 42
  • This is what I ended up doing. – Matt Sieker Feb 14 '11 at 17:04
  • 2
    dont bother with mapping. build your viewmodel directly by Querying off ISession, e.g Session.Query.Select(new ViewModel). It will save you alot of time & perf. only using Session.Get to get your full domain objects for mutating them. – mickdelaney Jun 13 '11 at 16:56