0

I have been developing my Models "model-first" by using the EDMX designer. I'm rather fond of it, but wondering how I can use this process to apply attributes, specifically DataAnnotations, to my model classes like so:

<DisplayFormat(ApplyFormatInEditMode:=True, DataFormatString:="{0:d}")>

I'm guessing that if I type those manually onto my model classes it will get overwritten whenever I update my EDMX file. What is the correct process here?

Thanks!

1 Answer 1

2

At the risk of repeating myself formatting attributes such as DisplayFormat should be applied to the view models and not the models. Models contain reusable business logic. View models on the other hand are specifically designed for a given view, so the formatting should be done on those view models. A controller always passes a view model to a view.

4
  • I apologize for making you repeat yourself, I had originally suspected that was the case but didn't find much in the way of confirmation of that suspicion. A question of implementation then: Should my ViewModel inherit the model object and overload the property(s) I want to add formatting attributes for?
    – Ben Finkel
    Apr 19, 2011 at 19:05
  • @Ben Finkel, the view model should not inherit from your model. Here's a typical scenario: 1. a controller action queries a repository and fetches a model, 2. the model is mapped to a view model (a tool such as AutoMapper could be very helpful in simplifying this task), 3. the view model is passed to the view in order to be displayed. This process works the other way round: a controller action takes a view model from a view, maps it to a model and passes the model to a repository for processing. Apr 19, 2011 at 19:07
  • That's interesting because I'm surprised there isn't some auto-generated mapping code for basic situations. However, that's a disucssion for another time and place. Thanks for the fast answer!
    – Ben Finkel
    Apr 19, 2011 at 19:17
  • Yes this seems overkill to have to create two duplicate models for simple applications just to be able to include data annotations on model-first generated class properties. It's possible to do just that when using Code-First approach it seems.
    – simbolo
    Mar 25, 2013 at 16:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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