views:

395

answers:

2

Hi, I would like to know the pros and cons of using EF4 Code-First approach. Can we duplicate all features that EF4 generated classes offer like Lazy Loading, loading related entities, etc?

Thanks

+1  A: 

Cons:

  • Since you have no EDMX, you can't pregenerate views
  • Not yet licensed for go-live. Hopefully, this will change soon.

Pros

  • Since there is no fixed schema, you can dynamically build one at runtime.

Most other things are exactly the same (lazy loading, explicit loading, etc.). A few more are matters of personal preference (the API).

Craig Stuntz
What about features like lazy-load, foregin keys, stored procedures, etc ?
Nazaf
@Craig "Since you have no EDMX, you can't pregenerate views"I am afraid this is not true. You can generate views based on your model classes - whether or not you have edmx files.
Bikal Gurung
@Bikal: What is the EdmGen syntax for this? An EF PM told me it could not be done a year ago. ...or are you confusing MVC views with EF views?
Craig Stuntz
@Craig. Apologies, I seem to have misunderstood you. I meant the MVC views and not the EF Views. Not too sure about EF views.
Bikal Gurung
@Bikal: I don't see how it would be possible. With code-only, you don't have an EF model until runtime, so you could not possibly do view generation before then.
Craig Stuntz
@Craig. Yes you can. When adding a new MVC view you select the typed view option and you will see a list of your model objects. Easy peasy !
Bikal Gurung
@Bikal: Once again, I am talking about EF views, not MVC views. The question did not specify MVC at all.
Craig Stuntz
+2  A: 

Pros

  1. Lightweight entity classes or POCO based.
  2. More control over entity classes since you code them yourself rather than depending on EF to generate them. This means you don't have to define partial classes to do data annotations.
  3. Option to never have to specify mapping anywhere. Convention takes over configuration.
  4. DbContext follows the repository pattern.
  5. Lazy loading, related entity loading all taken care of for you. For example a Post model can declare Author model in the POCO and EF Code first will map this relation automatically. Again use of convention makes us so productive.
  6. Works great for greenfield applications.
  7. ASP.NET MVC view generation works great.
  8. ModelBinder works as per normal.

Cons

  1. No API support for customizing the database mapping convention like in Fluent nHibernate.
  2. Bit difficult to map to existing databases.(This might change in the release version).

For sample code and mapping to existing databases using EF 4.0 Code First see this blog post. http://theminimalistdeveloper.com/2010/07/28/how-to-map-pocos-to-existing-databases-in-entity-framework-4-0-code-first-and-asp-net-mvc-2/

Bikal Gurung