Entity framework and Business Layer / logic - entity-framework

im doing some self-study on architecture of a MVVM-light - EF Application
im trying to build a product/Receipt like app.
I have a Db/EF with a Product and Receipt Table/Entity in a many to many relation.
then i have a DAL wich simply uses Linq to do simple CRUD.
the question is where and how to put my business logic in this app.
a couple of ideas came to mind
option 1
-make a ReceiptBo (Receipt business object)
wich inherit the Entity Receipt class and Icollection(ProductBo)
the ReceiptBo class would be responsible for adding Product,calculating total and subtotal and calling the Dal for inserting.
maby this option seemed a little overkill.
option 2
-put the calculating methods in the generated Entity objects by using partial classes
and simply using the BuisnessLayer to call the Dal.
this would make the Buisnesslayer Classes obsolete in my opinion and im not sure that Entity classes should be used for Business logic at all ?
option 3
-make the Business Classes but dont bother using inheritance, just add products to the Entity's and do the calculations there and call the Dal for insert.
wich seems simple but not very elegant.
option 4
-none of the above and im clueless
right now im not using WCF but the idea is that i want to make this app loosly coupled so that it would be easy to implement it and further extend it.
also im a little confused about what an Business layer is. in some examples it is more used like a Dal that also does the computing, then others say this is not done.
some help would be great. thx
ps: sorry for my bad english

Really, I would go simple here and choose a common multi-tier architecture designed as follows:
a data access layer (basically, your Entity Framework model along with all your entities)
a business layer that exposes methods to access to your entities (CRUD methods + any custom method that run some logic)
a service layer that exposes stateless methods through WCF (service+data contract)
the presentation layer (in your case using MVVM pattern)
Views (XAML pages)
ViewModels (C# classes)
Model is represented here by the entities that are exposed through WCF by the service layer
I wouldn't add any method directly in the entities. All methods are defined in the business layer, and exposed by the service layer.

Usually I keep my business logic in my ViewModels, not my Models, and I view EF objects as Models. At most, they'll have some basic data validation, such as verifying length or required fields.
For example, an EditRecieptViewModel would validate business rules such as verifying values are in a specific range, or verifying that users have access to edit the object, or performing some custom calculations when a value changes.
Also, don't forget that ViewModels should reflect the View, not a Model, so not every Model will have a ViewModel of its own

Related

MVC Business Logic + DAL + Mapping ViewModel with EF Model

I'm starting to develop an application, and I want to know the best practices to organize the architecture of the solution.
Should I use EF Class Model as my ViewModel?
Should I put all my queries and db access in the model? or create a Service to manage all Db concerns ?
I'm using EF with DB First, because the db is already developed.
Thanks!
There are much more complete descriptions of application architecture out there, but here's the $.25 description.
EF Class Models are for your communication with a data store
Data Transfer Objects (DTO) are how modules communicate among themselves
(WebAPI to MVC, etc.)
ViewModels supply the data your UI requires
Look up "Separation of Concerns" as it pertains to application architecture, it can save your butt. Often, developers will dual-purpose these entities leading to some hilarious results when you find you've painted a corner for yourself. Not so funny if you are the "painter".
On the other hand, keeping these models requires extra effort and the mappings take CPU cycles. Here's a concrete example:
WebAPI accesses People entity (EF class) and maps to a PeopleDTO (not all fields, maybe additional information) and returns this to your MVC controller. MVC controller takes the PeopleDTO and merges it with supporting lookup tables (more WebAPI calls) to create a PeopleVM (ViewModel) that is used by your Razor Page.
In the scenario I just outlined, there are three different types of People object but each could have very different contents dependent on the needs of that "layer". Lots of tools exist to make the mapping less painful.
Clear?

Entity Framework, MVVM, and Calculations Classes

I'm working on a database application that manages industry-specific inputs and then runs that information through somewhat complicated calculations, lookups, etc. to return a series of other values and a go/no-go conclusion.
I've decided to use Entity Framework (code first for provider independence) and WPF (MVVM pattern). I'm using the POCO entities as my data model and the view model is handling the usuals like basic data / business rule validation.
It seems EF + WPF/MVVM are great at displaying and validating input and getting it into the database for querying for your typical business application like a products, customers, orders setup. But it's not at all clear where to plug in a "calculations layer". Between the view models and the data models (my POCOs), things are already feeling a bit bloated, and now I'm facing adding another layer very much like the other two.
Perhaps the best way to approach this is to make the calculations layer a sort of meta-view model and push as much of the validations, change notification, etc. into them and run with lighter actual view models.
Anyone run into a situation like this?
Edit
Turns out what I really needed was to thin the view models and beef up the entities. So I lightened the view models, moved property change notification and basic validation to entities to allow for direct binding, and made calculation classes directly consume entities as well as adding some basic routines to entities. Thanks for the links on thought ADM articles #Peter Porfy.
For moving validation closer to entities, used Fluent Validation (excellent suggestion #Gloopy!). To make it easier to implement property changed notification on entities, adapted this technique. And to avoid having to create endless property wrappers in view model (to set HasChanges property) I used Josh Smith's PropertyObserver.
MVVM stands for Model-View-ViewModel, where the Model layer contains everything what models your actual domain problem.
So it depends on what you mean 'calculation layer'.
Put it where it belongs.
If the actual operation belongs to a domain entity, then you should put that logic into the entity. Don't make anemic domain models:
Article from Martin Fowler about ADM.
DDD works perfectly with EF code-first.
If something doesn't belong to any entity then probably you should expose that as a service. Then use that from your viewmodels through an interface.
A dependency injection container could make your life easier here, but you can live without it.
You aren't plugging another layer because it's the model layer. Your viewmodels should stay as thin as possible, just modelling your view's state and forwarding actual business operations to the entity/service classes.
I'd probably create an interface/object to handle calculations (or several if they can be split up logically) and pass that object in wherever you would want to use it. You might benefit from using a dependency injection framework maybe this post can help with that so you wouldn't have to explicitly instantiate your objects where you need them.
Also this post mentions FluentValidation.NET which may not apply completely but there are likely some good patterns to learn from/use there as well.

How to use Entity Framework(4) compiled queries in an n-tier layered application?

I have an n-tier application design problem with Entity Framework 4.
Server-side, my application has 3 layers :
- one Service layer (WCF)
- one Business layer
- one DataAccess layer (working with EF4)
The Entities are POCO, place in a independent project/assembly.
I'm using Dependency Injection for creating objects of the business and the DataAccess layers, therefore i only work with interfaces, and I have no dependency to EF in my business layer.
I'd like to use EF Compiled Queries to improve performances.
But my (business) queries are defined in the business layer, since in my architecture, the DataAccess is only providing the CRUD methods.
So the compiled queries should be defined in business layer, but i have no dependency to EF and don't want one to keep loose coupling, hence, i can't call the ObjectContext from there.
And defining the queries in DataAccess does not fit my application design.
So does anyone know if there is a generic way to inject the business queries from the business layer to the DataAccess layer, so that i can use them with Compiled queries ?
I've tried many things and looked everywhere, and couldn't find an answer to this ... :( looks like EF does not fit well with that kind of n-tier application.
Compiled query belongs to data access layer because it is data access specific feature dependent on data access classes. If your design doesn't accept this it is simply not ready for data access specific features = either change your design or don't use data access specific features.
The simplest way is to add compliled queries to your context and expose them as methods on the context:
public IQueryable<SomeEntity> SomeQuery(string someParam) {
return compiledQuery.Invoke(this, someParam);
}
Now you will add these methods to the interface for the context.
You can follow similar approach and expose compiled query on any data access interface visible in business layer.

MVC3 App/Service Layer/Repository Layer/POCO Classes/EF4 - Questions!

I am new to this whole design concept, and in reading for the last few weeks I have gathered a lot of information, but it seems scattered and conflicted. Terms are mixed, and I am just having a hard time wrapping my mind around this.
The pattern I am using is like this and assume the flow as follows:
MVC Application
The controller(s) process the request/response from the client for a given view. Inside the controllers action methods, they contact the services (Service Layer) and either request objects to build the view models, and sen the objects from the view models back.
View Models
I am using strongly typed view models to and from the views.
Are view models DTO's? Should they contain just simple properties like Name, AddressLine1, Address City, etc, or should they contain complex properties, multiple objects, etc.
Is the validation in the view model. If so would it be validation like required fields, field length, etc. Then validation like user name already exists, or where you would need to interact with other objects in the service layer?
Can the view models just contain the POCO classes returned from EF, or should I be using the AutoMapper?
If using AutoMapper and DTO, are DTO's clones of the POCO classes?
Would you map in the controller, view model, or in the service layer below?
Services
To me, the service(s) are objects that contact the repository(s) to get POCO objects back from the EF. This is where all of my business logic is. Once the service hands an object back to a repository to be persisted to the EF, they are considered valid objects. Is this correct?
Repositories
There is no business logic in them, they are just used to transport objects between the service(s) and the EF. Is this correct? I am implementing Interfaces here with generic repository. Then you could extend the generic repository for special needs?
Questions About Terminology
1) Is a business object equal to a domain object? How much logic should a domain object contain?
2) Is the domain model the EF model? I am using the Model-First approach.
3) Dependency Injection - Should I be using this? I understand how it works, just don't get the real benefit. I was playing with Ninject.
I think the community would benefit from some sort of wiki that contained all the best practices with code samples. Is there something like that out there? A lot of the samples out there are very simple, and a lot of the Microsoft samples do not use this pattern even when claiming to.
Thanks in advance to everyone who has and will help me with this.
BTW - I think StackOverflow needs a little, "Buy Me A Beer" button next to the "Accept Answer" checkbox :)
Are view models DTO's?
Could be considered a sort of data transfer objects between the controller and the view.
Should they contain just simple properties like Name, AddressLine1, Address City, etc, or should they contain complex properties, multiple objects, etc.
Ideally simple properties but could also aggregate other view models but no models there (ex: like EF models).
Is the validation in the view model.
There are two type of validation logic: business validation (ex. username already exists) which goes into the service layer and UI validation (ex: username is required) which goes into the view model.
Can the view models just contain the POCO classes returned from EF, or should I be using the AutoMapper?
No EF in view models. View models are POCO classes with simple properties and other complex properties pointing to other view models. They could also contain methods in order to properly format the data that will be presented on the particular view those models were intended for.
If using AutoMapper and DTO, are DTO's clones of the POCO classes?
Not sure I understand this question.
Would you map in the controller, view model, or in the service layer below?
The controller.
To me, the service(s) are objects that contact the repository(s) to get POCO objects back from the EF. This is where all of my business logic is. Once the service hands an object back to a repository to be persisted to the EF, they are considered valid objects. Is this correct?
Yes.
Is the domain model the EF model?
If you are using EF Code first approach then yes, otherwise no (if EF pollutes the domain with EF specific attributes and classes).
There is no business logic in them, they are just used to transport objects between the service(s) and the EF. Is this correct?
Yes.
I am implementing Interfaces here with generic repository. Then you could extend the generic repository for special needs?
Yes, but don't get too fancy. Normally Repositories are for CRUD operations. It's services that should contain the business logic.
Is a business object equal to a domain object?
Yes.
How much logic should a domain object contain?
This will depend on the amount of domain logic you have for the particular project you are working and on any existing domain logic you could reuse from older projects you or someone else have worked on.
Dependency Injection - Should I be using this?
Yes, absolutely.
I understand how it works, just don't get the real benefit
It provides weaker coupling between the different layers of your application which in turns makes them easier to unit test and reuse in other projects.
I think the community would benefit from some sort of wiki that contained all the best practices with code samples.
I agree.
Is there something like that out there?
I doubt it.
BTW - I think StackOverflow needs a little, "Buy Me A Beer" button next to the "Accept Answer" checkbox
Can't agree more.

Where "ADO.NET Entity Framework" files in 3 layer architecture?

If I use ADO.NET Entity Framework in our project and we depend on a 3-layer architecture pattern that we have ( presentation layer - business layer - data access layer ) a project for each layer.
So when I make an entity model file where can I put it in the DAL or BL? If I put it in the DAL and from the presentation layer want to access a domain object in it through the business layer so we need to add a reference to the DAL in the presentation layer. Also, how do I get that type of an object as it is created in the DAL? On the other hand should I put the entity model file in the business layer? Which is the better and why?
Ideally, the EntityFramework generated code makes up your data layer. You would basically have some repetition then in your business layer if you needed the same sorts of objects in your business layer as you have in your data layer. Unfortunately, EntityFramework doesn't really help you at all with your business layer.
Now, you'll also read things about EntityFramework that say you can/should use it as a combined data/business layer. That violates Separation of Concerns, so I would guide you away from it, but I'm sure a ton of people do it anyway. If you wanted to move from EntityFramework to NHibernate some day, you'd be best off trying to isolate your ORM from the rest of your code base and minimize any coupling to the ORM (often through implementing something like a Repository pattern).
People who talk the language of MVC will often use EntityFramework as the Model and may or may not distinguish between a data layer and a business layer (which generally would both live in the Model). Even if you use MVC, I still believe you should decouple your data access from your business rules and business logic.
You can place the entities in a separate class library project, for example: Common Entity Library. This library can be referenced in any other app layers. You can then work with collections across application domain.
As I see it the Entity Framework is your DAL. It provides the needed tools to abstract the Model objects exposed by the Entity Framework from the persistance services of a backend database.
The Entity Framework straddles both the Business Layer and the DAL from this old three layer pattern. My advice is if you going with the Entity Framework is stop thinking in terms of Presentation->Business->Data and think more in terms of View->Model.