EF 4.1 Code First - What pattern should I use? - entity-framework-4

I am learning EF Code First and I am struggling a bit with what patterns to use in my application. I have read many conflicting sugestions and arugments some stating you should use the Repository pattern while others say doing so is redundant, which I tend to agree.
Here is my delima:
Suppose I am building a REST Web Service that is going to allow me to manage customers. This service will allow me to add customers, delete customes, and edit customers, and find customers.
Should I:
A.) My question comes down to where should my business logic go. Should I have a CustomerManager class that provides Add, Edit, Delete, and Find methods that take in a Customer entity? Should my validation logic go in those methods?
B.) Should I use an Active Record style of development when my Customer entity would have Save(), Delete(), and Find() methods on it withall validations login being done inside of the Customer class?
C.) Should I do some type of hybrid, where simple validation logic is on the entity itself. This could be done through code first attributing. I could also have a simple save method on the entity. Then, I could do complex business validation logic, deletes(), finds(), and multi-entity saves in a CustomerManager class?
I kind of lean toward option C. In the past I have typically used Manager/Service classes keeping my entities pretty simple. However, since code first does entity property validation on the entity level, it seems like maybe all simple entity validation should go there.
I realize this could be somewhat of a religious topic, but I would like to get some other options on what would be the best way to put together a solid application.

EF 4.1 Code first combine unit of work with data mapper pattern.
So, I would not recommend use active record pattern.
Repository pattern with entity framework is common solution. If you want some simple validation logic, you can use DataAnnotations which works with entity framework well.
Here is simple example of implement repository pattern with EF :
http://www.efekaptan.com/repository-pattern-with-entity-framework-code-first-4.1

Related

Where should I add a List All Users function when using MVC?

I'm aware that in model-view-controller, the Model is the class part.
If I have a User class and instantiate an object, the object must refer to a single user from the database.
So I'll have the CRUD methods on the user, for that specific user.
But if I need a function to run a SELECT * FROM Users, should I create a function within the User class? Or a function in a helper file? Or in the controller? Where should it go, in order to respect the MVC pattern?
I mean, it makes no sense to instantiate a User object just to run a function to display the Users table.
I'm not sure if this will raise "primarily opinion based" flags. I just don't know where those functions should go. If you guys consider the question worth closing, it's ok. But tell me in the comments in which stack community I should ask this.
Back up a bit. Let's go foundational for a moment.
In the MVC pattern
The model is your state (in simple terms), meaning a representation of the data important to the business functionality you are working with
The view is a way of presenting the state to the user (NOTE user here could be another system, as you can use MVC patterns for service endpoints)
The controller ensures the model gets to the view and back out of the view
In a system designed with good separation of state, business functions are not present in the model, the view or the controller. You segregate business functionality into its own class library. Why? You never know when the application will require a mobile (native, not web) implementation or a desktop implementation or maybe even become part of a windows service.
As for getting at data, proper separation of concerns states the data access is separate not only from the model, view and controller, but also from the business functionality. This is why DALs are created.
Before going on, let's go to your questions.
should I create a function within the User class? This is an "active record" pattern, which is largely deprecated today, as it closely couples behavior and state. I am sure there are still some instances where it applies, but I would not use it.
Or a function in a helper file? Better option, as you can separate it out. But I am not fond of "everything in a single project" approach, personally.
Or in the controller? Never, despite Scott Gu's first MVC examples where he put LINQ to SQL (another groan?) in the controller.
Where should it go, in order to respect the MVC pattern?
Here is my suggestion:
Create a DAL project to access the data. One possible pattern that works nicely here is the repository pattern. If you utilize the same data type for your keys in all/most tables, you can create a generic repository and then derive individual versions for specific data. Okay, so this one is really old, but looking over it, it still has the high level concepts (https://gregorybeamer.wordpress.com/2010/08/10/generics-on-the-data-access-layer)
Create a core project for the business logic, if needed. I do this every time, as it allows me to test the ideas on the DAL through unit tests. Yes, I can test directly in the MVC project (and do), but I like a clean separation as you rarely find 0% business rules in a solution.
Have the core pull the data from the DAL project and the MVC project use the core project. Nice flow. Easy to unit test. etc.
If you want this in a single project, then separate out the bits into different folders so you can make individual projects, if needed, in the future.
For the love of all things good and holy, don't use the repository pattern. #GregoryABeamer has a great answer in all respects, except recommending you create repository instances to access your entities. Your ORM (most likely Entity Framework) covers this, and completely replaces the concepts of repositories and unit of work.
Simply, if you need something from your database, hit your ORM directly in your controller. If you prefer, you can still add a level of abstraction to hide the use of the ORM itself, such that you could more easily switch out the data access with another ORM, Web Api, etc. Just don't do a traditional unit of work with tens or hundreds of repository instances. If you're interested, you can read a series of posts I wrote about that on my blog. I use the term "repository" with my approach, but mostly just to contrast with the typical "generic" repository approach you find scattered all over the interwebs.
I'd use some kind of 'Repository' layer. Then, my controller calls the UserRepository GetAll method and sends the data to View layer.

Any tool to autogenerate View Models from Entity Framework Domain Models?

I am using MVC3, ASP.NET 4.5, C#, MSSQL.
I need to create ViewModels from my Domain Model that is automatically generated by Entity Developer.
Once I create the relevant ViewModel for an entity I can comment out non required properties for a particular View.
However there is the ongoing concern that once an entity is upgraded then the ViewModel could become out of sync, and I want to minimise the risk/effort in fixing this.
Thanks in advance.
I see the same complaint endlessly about using view models. True, they can be repetitive in nature, but copy and paste works beautifully there. If you so wanted, you could even design an interface that both your model and view model must implement, which can help you keep the two in sync somewhat. However, I think you'll find that the two will diverge more than you think.
As far as validation goes, this is also a common complaint, but it's actually a symptom of bad design. Your entity class should only have validation specific to the database, which you'll find is actually pretty sparse. Entity Framework actually does a fantastic job translating most of the properties inherent limitations to the database. For example, a DateTime property's column is set as NOT NULL by default, because the C# type itself cannot be null. There's no need to add something like [Required], because the behavior is inherent.
Other types of validations such as regex are totally inappropriate for a domain model because there's no correlation to anything happening at the database level. It's entirely for the UI, and thus belongs on your view model. I think you'll find that if you evaluate all the things you're trying to validate on your domain model, you'll find most if not all should be strictly on your view model(s) instead.

What is the best practice, Entity Framework Models or MVC Models?

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.
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:
Domain Entity
View Model
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...
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.

Can a pure DDD approach be used with NHibernate?

I've been reading up on DDD a little bit, and I am confused how this would fit in when using an ORM like NHibernate.
Right now I have a .NET MVC application with fairly "fat" controllers, and I'm trying to figure out how best to fix that. Moving this business logic into the model layer would be the best way to do this, but I am unsure how one would do that.
My application is set up so that NHibernate's session is managed by an HttpModule (gets session / transaction out of my way), which is used by repositories that return the entity objects (Think S#arp arch... turns out a really duplicated a lot of their functionality in this). These repositories are used by DataServices, which right now are just wrappers around the Repositories (one-to-one mapping between them, e.g. UserDataService takes a UserRepository, or actually a Repository). These DataServices right now only ensure that data annotations decorating the entity classes are checked when saving / updating.
In this way, my entities are really just data objects, but do not contain any real logic. While I could put some things in the entity classes (e.g. an "Approve" method), when that action needs to do something like sending an e-mail, or touching other non-related objects, or, for instance, checking to see if there are any users that have the same e-mail before approving, etc., then the entity would need access to other repositories, etc. Injecting these with an IoC wouldn't work with NHibernate, so you'd have to use a factory pattern I'm assuming to get these. I don't see how you would mock those in tests though.
So the next most logical way to do it, I would think, would be to essentially have a service per controller, and extract all of the work being done in the controller currently into methods in each service. I would think that this is breaking with the DDD idea though, as the logic is now no longer contained in the actual model objects.
The other way of looking at that I guess is that each of those services forms a single model with the data object that it works against (Separation of data storage fields and the logic that operates on it), but I just wanted to see what others are doing to solve the "fat controller" issue with DDD while using an ORM like NHibernate that works by returning populated data objects, and the repository model.
Updated
I guess my problem is how I'm looking at this: NHibernate seems to put business objects (entities) at the bottom of the stack, which repositories then act on. The repositories are used by services which may use multiple repositories and other services (email, file access) to do things. I.e: App > Services > Repositories > Business Objects
The pure DDD approach I'm reading about seems to reflect an Active Record bias, where the CRUD functions exist in the business objects (This I call User.Delete directly instead of Repository.Delete from a service), and the actual business object handles the logic of things that need to be done in this instance (Like emailing the user, and deleting files belonging to the user, etc.). I.e. App > (Services) > Business Objects > Repositories
With NHibernate, it seems I would be better off using the first approach given the way NHibernate functions, and I am looking for confirmation on my logic. Or if I'm just confused, some clarification on how this layered approach is supposed to work. My understanding is that if I have an "Approve" method that updates the User model, persists it, and lets say, emails a few people, that this method should go on the User entity object, but to allow for proper IoC so I can inject the messagingService, I need to do this in my service layer instead of on the User object.
From a "multiple UI" point of view this makes sense, as the logic to do things is taken out of my UI layer (MVC), and put into these services... but I'm essentially just factoring the logic out to another class instead of doing it directly in the controller, and if I am not ever going to have any other UI's involved, then I've just traded a "fat controller" for a "fat service", since the service is essentially going to encapsulate a method per controller action to do it's work.
DDD does not have an Active Record slant. Delete is not a method that should be on an Entity (like User) in DDD.
NHibernate does support a DDD approach very well, because of how completely divorced it remains from your entity classes.
when that action needs to do something
like sending an e-mail, or touching
other non-related objects
One piece of the puzzle it seems you are missing is Domain Events. A domain entity shouldn't send an email directly. It should raise an event in the Domain that some significant event has happened. Implement a class whose purpose is to send the email when the event occurs, and register it to listen for the Domain Event.
or, for instance, checking to see if
there are any users that have the same
e-mail before approving
This should probably be checked before submitting the call to "approve," rather than in the function that does the approving. Push the decision up a level in calling code.
So the next most logical way to do it,
I would think, would be to essentially
have a service per controller
This can work, if it's done with the understanding that the service is an entry point for the client. The service's purpose here is to take in parameters in a DTO from the front end/client and translate that into method calls against an entity in order to perform the desired funcitonality.
The only limitations NHibernate creates for classes is all methods/properties must be virtual and a class must have a default constructor (can be internal or protected). Otherwise, it does not [edit] interfere with object structure and can map to pretty complex models.
The short answer to you question is yes, in fact, I find NHibernate enhances DDD - you can focus on developing (and altering) your domain model with a code first approach, then easily retro-fit persistence later using NHibernate.
As you build out your domain model following DDD, I would expect that much of the business logic that's found you way into you MVC controllers should probably reside in your domain objects. In my first attempt at using ASP.NET MVC I quickly found myself in the same position as yourself - fat controllers and an anemic domain model.
To avoid this, I'm now following the approach of keeping a rich domain model that implements the business logic and using MVC's model as essentially simple data objects used by my views. This simplifies my controllers - they interact with my domain model and provide simple data objects (from the MVC model) to the views.
Updated
The pure DDD approach I'm reading about seems to reflect an Active Record bias...
To me the active record pattern means entities are aware of their persistance mechanism and an entity maps directly to a database table record. This is one way of using NHibernate e.g. see Castle Active Record, however, I find this pollutes domain enitities with knowledge of their persistence mechanism. Instead, typically, I'll have a repository per aggregate root in my domain model which implements an abstract repository. The abstract repository provides basic CRUD methods such as:
public IList<TEntity> GetAll()
public TEntity GetById(int id)
public void SaveOrUpdate(TEntity entity)
public void Delete(TEntity entity)
.. which my concrete repositories can supplement/extend.
See this post on The NHibernate FAQ which I've based a lot of my stuff on. Also remember, NHibernate (depending on how you set up your mappings) will allow you to de-persist a complete object graph, i.e. your aggregate root plus all the objects hanging off it and once you've finished working with it, can cascade saves through you entire object graph, this certainly isn't active record.
...since the service is essentially going to encapsulate a method per controller action to do it's work...
I still think you should consider what functionality that you currently have in your controllers should, more logically, be implemented within your domain objects. e.g. in your approval example, I think it would be sensible for an entity to expose an approve method which does whatever it needs to do to within the entity and if, as in your example, needs to send emails, delegate this to a service. Services should be reserved for cross-cutting concerns. Then, once you've finished working with your domain objects, pass them back to your repository to persist changes.
A couple of books I've found useful on these topics are:
Domain-Driven Design by Eric Evans
Applying Domain-Driven Design and Patterns by Jimmy Nilsson

Getting Started with Repository Pattern

I'm trying to get started with the repository pattern and ASP.NET MVC, and I can't help but believe I'm missing something. Forgive me if this is a stupid question, but it seems to me like an implementation violates DRY exponentially. For example, in my (admittedly novice) understanding in order to implement this, I would have to:
Create my database model (Currently using Linq to Sql)
Create a IRepository for each concept (table or group of related tables)
Create an implementation for each IRepository
Do we return L2S objects or some sort of DTO?
Create viewmodels which either are containers or copies of the data
Use some method of DI (Windsor or Unity?) on the controllers
While I realize scalability and portability come at an expense, it just feels like I'm missing something?
I tried to implement the Repository Pattern in LINQ 2 SQL and it doesn't work very well, mainly because L2S doesn't use POCOs and you have to map to DTOs all the time as you mention. Although you could use something like AutoMapper, L2S just isn't a very good fit for the Repository Pattern.
If you're going to use the Repository Pattern (and I would recommend it), try a different data access technology such as NHibernate or Entity Framework 4.0's POCO support.
Also you wouldn't create a Repository for each and every table, you create a Repository per Domain Aggregate, and use the Repository to access the Aggregate's Root entity only. For instance, if you have an e-commerce app, with Order and OrderItem entities, an Order has one-or-many OrderItems. These 2 entities are part of a single Aggregate, and the Order entity is the Aggregate Root. You'd only create an OrderRepository in this case, NOT an OrderItemRepository as well. If you want to add new OrderItems you'd do so by getting a reference to the Order entity, then adding the new OrderItem to the Order's Items collection, then saving the Order using your OrderRepository. This technique is called Domain Driven Design, and it's a very powerful paradigm to use if you have a complex Domain Model and business rules in your application. But it can be over kill in simple applications, so you have to ask yourself does the complexity of your Domain Model warrant using this approach.
In terms is adhering to DRY, normally I create a base Repository class that has common methods for Save, Delete, FetchById, that sort of thing. As long as my Repository classes implement this base class (OrderRepository, ProductRepository etc.) then they get these methods for free and the code is DRY. This was easy to do in NHibernate because of POCO support, but impossible to do in Linq 2 SQL.
Don't worry too much about sending your Domain Models directly to the view, most dedicated ViewModels look almost identical to the Domain Model anyway, so what's the point. Although I tend to avoid using the DM for posting data back to the server because of under/overposting security concerns.
If you follow this POCO approach (and ditch LINQ 2 SQL, honestly!!), you end up with only one class (your POCO entity) instead of 3 (L2S class, DTO and ViewModel).
It is possible to implement the Repository Pattern badly, so tread carefully, read a few tutorials, blog posts books etc. (I recommend Steven Sanderson's book, especially look at the Pre-Requisites chapter) But once mastered, it becomes a very powerful way to organise the complexity of hydrating Model objects to and from a data-store. And if you use Repository interfaces (IOrderRepository etc.) and have them injected via an IOC Container, you also gain the benefits of maintainability and unit testability.
Do you understand why your doing these things or are you just following along with a blog article or other source?
Don't implement the Repository pattern because its the new hotness. Implement it because you understand how these separation of concerns helps your project and overall quality of your code.
From your ?'s in your question it sounds like you need to do some more reading before you implement. Your probably missing a meaningful understanding of the overall architecture approach. Please don't take this the wrong way and I'm not trying to be negative.
Side Rant:
Obviously something is missing from the newest repository hotness picture because the confusion about implementation details like single Repository vs. Many/Grouped "DTO or not to DTO" are just so ambiguous and subjective. This is a "nickle question" that pops up again and again.
This has been brought up before, at first glance certain aspects of properly separating concerns does seem to violate DRY.
As you've mentioned MVC have you read Steve Sanderson's Pro ASP.NET MVC 2 Framework book? It spends a great deal of time explaining why using the repository pattern is a good idea.
You might find that, for the projects you're working on, it isn't appropriatte, that's okay. Don't use it and see if you come across problems that this could have addressed. You don't need to be a developer for long to realise how crucial it is to keep different parts of your application as loosely coupled as possible.

Resources