I have my Fluent NHibernate setup code in a DataAccess project which is accessed from my Web application.
As part of the NHibernate configuration I defined a Model to be used when mapping to the database.
public sealed class MyTypeMapping: ClassMap<MyType>
This model MyType is identical to a model that I require in my web layer to be passed to a view. I’d also like to add some additional meta data to this model such as Required and DisplayName.
I’m sure this is a common scenaro where models in the data access layer are the same as models required in the web layer.
How is this commonly handled? Is it an accepted practice to make a view dependent on a model in the data access layer or should I simply create a ViewModel to abstract the details away from the view?
I’m quite new to ORM and it feels odd to have my models outside of my Models folder in the MVC project and duplicating the model doesn’t feel right either.
How do you handle this?
For some people maybe, for me no.
That’s what I would do.
Of course if you don’t want to follow my suggestion of using view models you have a couple of possibilities. So let’s suppose that you have the following domain model:
but you wanted to associate some metadata to it.
The first possibility that you have and which is built-in is to use the
[MetadataType]attribute:and have a separate class for the metadata:
But still your DAL must know about metadata and presentation logic which is not quite good. The
MyDomainModelMetadataclass must be defined in your DAL because attributes represent metadata that is baked into the assembly at compile time.Which brings us to the second possibility consisting of writing a custom model metadata provider:
which will be registered in your
Application_Startand which will replace the default metadata provider:Now you can get rid of the
MetadataTypeattribute on your domain model and have theMyDomainModelMetadataclass in your UI layer (the MVC application itself).