So I worked on my first MVC 3 application. This was also my first time using Entity Framework. I had read a lot about EF and even did some comparisons between EF & NHibernate - buying and reading books on both.
I am still getting used to writing 3-tier applications (I am pretty old-school), but I can clearly see the benefit. However, one thing that disturbs me a little is the use of POCOs with EF. If you simply break out your EF for dummies type of example and use the modeler to create your objects, you will end up with some fat objects that have persistence properties/methods on them. Well, this makes them hard/impossible to use across tiers. Remember, the Business Logic Layer (BLL) and Interface Layer should not know anything about persistence.
So what should you do?
Well, in the application I was working on, the lead programmer (a consultant) created the EF classes in the Data Access Layer (where they should be), then created a new project/assembly with POCOs (Plain Old CLR Objects) that he called Business Entities. These business entities mimic'ed the EF classes that were created, but without any of the persistence methods on them. He then proceeded to make a "copy" function for each class to copy the properties from the EF object to the BE object and back again. An example might be CustomerEF2BE and CustomerBE2EF.
This method did not "feel right" to me. While I agree that the EF objects should not be used to the higher tiers, I don't believe that you should have to incur the overhead of creating these copy from/to helper methods. There are a few good tutorials on using POCOs directly with EF:
POCOs in EF, Part 1: The Experience
POCOs in EF, Part 2: Complex Types/Deferred Loading
POCOs in EF, Part 3: Change Tracking with POCOs
OK, so EF has a new CTP4 which include a "Code First" model. This allows you to define your POCO FIRST, then generate the database schema from your POCO. You never even have to use the EF Modeler app. This seems much more natural to me! Here is a link to a sample app using this method:
Scott Gu's Code First EF Example
No comments:
Post a Comment