Question

When using Entity Framework with Code-First, what is the best practice when calling database data?

This is my first time using Entity Framework with MVC and noticed that it automatically builds Models in my DataLayer. I also have the basic Models within my MVC UI which allow me to manipulate and display the data within my Views. I currently grab the data using my Workflow layer, and then AutoMap the Database Model to my UI Model to display the data.

Is this the best practice? Should I be using the Entity Framework Models instead of my UI Models? Or this even possible to do cleanly?

Any information on the matter would be appreciated.

Was it helpful?

Solution 2

The POCOs created by EF are supposed to be used as your model. The general idea is that you have EF providing access to your database. You query EF using LINQ and/or extension methods and end up with an object or collection of objects that you display on your UI by binding them in WPF. That is of course if you're using WPF as opposed to the older WinForms. I can tell you from experience that it's a very streamlined process once you become familiar with the technologies. That's how a very basic setup would work.

A more advanced way of going about it is adding architectures like Model-View-ViewModel (MVVM) and possibly the repository pattern into the mix at which point you get better separation of code and presentation at the cost of increased complexity.

I don't know what flavor of MVC you're using and how it can be made to intermingle with the above, but if you want to know more about how EF was envisioned to work you should look into the technologies I've listed above.

OTHER TIPS

It's up to you really. If you like to re-use the same EF entities for your view models as well; go ahead. Personally, I prefer not to. This is because you normally end up adding a bunch of properties to the class that have nothing to do with what's stored in the data and yes; I know you can use the NotMapped attribute like this:

[NotMapped]
public string MyExtraProperty { get; set; }

but I prefer not to. Additionally, you end up adding [Display] and other attributes to your properties and before you know it, you've got something decorated with both data specific and UI specific attributes and it can get messy if you're not careful.

So for me; I have the following:

  1. Domain Entity
  2. View Model
  3. Service/Facade/Repository

Controller calls repository to get the domain entity and converts it to a view model for displaying.

I find that to be a cleaner approach, but maybe that's just me.. the most important thing is to just choose one way and stick with it for the sake of consistency and clarity of code, but either method is acceptable.. "whatever floats your boat" as they say...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top