Friday, May 29, 2015

Entity FrameWork Code First - Introduction


Code First approach was introduced with Entity Framework 4.1. With code first, you can start building your classes based on your business requirement first and entity framework will take care of creating the databases and tables. (If you don't want your databases to be automatically created, you can turn off this feature).

Why Code First ?

Though Database First/Model First approaches seem to be effortless at the beginning, it becomes difficult when you want to have more and more customization to your properties/database columns. With these approaches, .edmx model files will be auto-generated. Yes, it seems to have taken care of most of your job. But you can never alter these files, because any changes that you make will be lost when you regenerate the model files again for some reason.(eg. adding a column).  For example, if you want to have a different display name for a column (rather than the one in the database), you will have to create a partial class and extend your model class. You have to do this for almost every model that you are creating.

But with code first approach, you have more control over customizing your columns(making it a required field/read only etc..) as the model that you hand code becomes your database. You can precisely and easily specify the relationship and the constraints. Most of all, Entity Framework provides an excellent version control of your database which will otherwise be cumbersome.

When you are planning to create a small project, you can very well use database/model first approaches as it will greatly reduce your time. But for mediocre to big projects, code first is always a recommended approach.

Next>> Installing/Updating Entity Framework

No comments:

Post a Comment