Search code examples
c#entity-frameworkpoco

OnModelCreating vs DataAnnotations for Database Configuration


I have an ntier solution which has a Domain project for my POCO classes. I want to generate the database with some table fields constrianed to a particular length. Now I see two ways of doing this, either Data Annotations in the POCO classes themselves or using the OnModelCreating method in my DbContext but which is the best way?

My concerns with the OnModelCreating approach is that this is then specific to Entity Framework. Should I switch to another ORM, the database conguration is lost unless I re-implement it.

With the Annotations approach, I end up cluttering my models and worry they lose the "POCO" tag. I am also unsure if other ORMs would respect the Annotations. On the other hand, all the information about what the database should look like is tied to the model so easy to maintain.

Any thoughts to point me in the right direction?


Solution

  • OnModelCreating is better. Some mapping features are not available through data annotations. Moreover as you already mentioned in some cases data annotations goes against POCO principle because your classes can contain information about persistence and even some data annotations currently need EntityFramework.dll referenced in your domain project.

    Also be aware that data annotations are MS specific feature used mostly by MS tools. If you want to use them with other ORM you will have to implement conversion from data annotations to ORM's mapping description (unless it already exists).