I'm developing a project using a layered architecture. I have a DAL in which i'm using Entity Framework, a business logic layer which consumes the objects returned by the DAL and an app layer.
I'm not entirely sure i'm thinking this right, so i'll just ask you what you think.
My DAL is based on mappers. I have types - mappers - that the BLL uses to operate on my data. These mappers return DTO's, because i did not want to expose to my BLL any EF objects so their implementations are not dependent on EF to work.
All these mappers do are CRUD actions on a single 'table', like:
using (var contex = new EFEntities()){
var obj = (from x in context.Table where x.ID == param select x).SingleOrDefault;
return Map(x.ToList());
}
The Map method maps the EF object to a DTO, which has only some properties to map the values i want to expose.
Is there a more elegant approach to this? I am just using EF to facilitate the access to my database - i don't have to write any ADO.NET code.
Any input on this would be welcome.
Thanks.
I have a DAL in which i'm using
Entity Framework, a business logic
layer which consumes the objects
returned by the DAL and an app layer.
That is a perversion, given that you are putting a complete object layer into your DAL. EF is a lot more than a DAL.
a business logic layer which consumes
the objects returned by the DAL and an
app layer.
The term you may want to look up for that is "anemic object model", and it is not a nice term.
Is there a more elegant approach to
this?
Don't fight EF. if you dont like it, don't use it - there are a LOT better frameworks around.
Related
I am new to a 15 year old application. The team lead has started using Entity Framework + alongside existing WebForms + Sprocs.
Some POCOs (domain entities) in EF have properties containing references to the DbContext, usually parent objects at the top of an object graph. As I attempt to write tests, I continually get Context Disposed exceptions.
public EmployerService(int UserID, Entities entities) // business layer
{
this.UserID = UserID;
_entities = entities;
}
internal Employer CreateEmployer()
{
Employer employer = _entities.Employers.Create();
employer.MasterItem = _entities.MasterItems.Create();
employer.MasterItem.LastModified = _entities.ItemLastModifieds.Create();
employer.DBContext = _entities;
...
return employer;
}
More to the point, the project references are not clean. The POCOs reference Data and Business logic layers. I am building a case to get the DbContext references out of the POCO objects, but my search is just beginning.
So my question is, what design principles support or reject referencing the DAL layer from the POCOs?
Your DAL layer sneaks into Business Logic layer. Service now tightly coupled to Entity Framework (BTW I don't think it's good idea to add reference to EntityFramework.dll into your domain project). Consider we are moving to NHibernate. What you should change? Everybody would think it's a DAL task. But wait guys, I have some DAL in my domain! We should change EmployerService class.
So, keep your domain entities persistent ignorant. Especially keep them ignorant of concrete persistence technology you are using. And I think better place for Employer creation is a factory. Also I don't understand why you are not using simple constructors here? Looks like you can avoid Entity Framework usage during Employer creation.
The most vocal design principle here is that you're having problems with the current design.
DbContext is supposed to be used as a short-living - and it's not meant to be stored for later. The reference you're holding doesn't mean much, as it gets Disposed.
To the very least you should check if it's Disposed (you can do that by overriding Dispose I guess, setting a flag or something). But what to do if it is?
Basically, if you still do use it that way - make sure your POCO objects are `short-lived' as well - but that gets painful I'm sure.
I have two EntityFramework models that I want to combine into a single DTO. Is there a way to do this? There are a couple ideas in the following question, but you would either have to create a composite model, or lose the ability to call Mapper.AssertConfigurationIsValid to verify all of the properties will be set.
Is it possible to map multiple DTO objects to a single ViewModel using Automapper?
single-viewmodel-using-automappe
From my point of view, It is highly recommanded to create a composite type for merging entities. Entities are part of your Business logic or your Domain logic (depending on your architecture), whereas DTO are part of Presentation logic or Transport layer. You can create an explicit mapping that can be easily tested ; automatic mapping (create maps without options) is good for testing only. If you are using a DTO, then you will probably use it somewhere : in WCF ? as a ViewModel ?
Visual Studio and .Net Framework can manage many files and you have not to sacrifice testability or simplicity (do you know "Technical Debt"?)
Note : The role of Mapper.AssertConfigurationIsValid is to validate all mapping, generated by automatic or explicit mapping. I suggest you call this every time.
Lets say we are using DTO objects to transfer data between service layer and Presentation (MVC) layer.In this case the presentation layer can only access DTO objects. Therefore we can't use lazy loading functionality in Entity framework.
Am I right here? Please give your suggestions.
(My DTO are not the entities in EF and I have implemented repository and unit of work pattern)
You can use lazy loading but only on your service side when you are working with attached entities.
First put your definition right: Are your DTO objects also your entities in EF 4.1? Are they (also) your models and do they contain business logic?
If so, i would recommend turning off proxy creation ( myDbContext.Configuration.ProxyCreationEnabled = false; ) since they cant be serialized easily. Then use a repository for dataAccess where in the CRUD methods, you specify the right entity states like: http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx
We are in a process of designing an application with approx 100 tables and complicated business logic. Windows Forms will be used on the client side and WCF services with MSSQL on the server.
Custom DTOs are used for client-server communication, business entities are not distributed.
Which variant of Entity Framework to use (and why):
EF 4.0 EntityObjects
EF 4.0 POCO
EF 4.1 DbContext
Something else
Database-first approach is a requirement.
Also, is it worth implementing a Repository pattern? It seems a bit redundant, as there is one level of abstraction in the mapping itself and another one in the use of DTOs. I'm currently leaned towards using auto-generated extendable repositories for each entity returning IQueryable, just to have a place to put common queries, but still allowing querying entity model directly from the Service Layer.
Which variant to use? Basically once you have custom DTO the only question is do you want to have control over entities code (their base class) and make them independent on EF? Do you want to use code first? If the answers to all questions are no then you can use EntityObjects. If you want to have entities persistence ignorant or use custom base class you should go to POCO. If you want to use code first or new DbContext API you will need EF 4.1. Some related topics:
EF 4.1 Code-first vs Model/Database-first
EF POCO code only VS EF POCO with Entity Data Model (this was related to CTP)
ADO.NET DbContext Generator vs. ADO.NET POCO Entity Generator
EF Model First or Code First Approach?
There are more things to consider when designing service layer. You should be aware of complications you will have to deal with when using EF in WCF. Your service will provide data to WinForms application and it will work with them in "detached mode". Once user will do all changes he wants to do he will post data back to the service. But here comes the problem - you must tell EF what has changed. If you for example allow user to change order with all its order items (change quantity in items, add new items, delete some items) you must say EF exactly what has changed, what was added and what was deleted. That is easy when you work with single entity but once you allow user to change object graph (especially many-to-many relations) then it is quite tough. The most common solution is loading the whole graph and merge the state from incoming DTOs to loaded and attached graph. Other solution is using Self tracking entities instead of EntityObjects/POCOs + DTOs.
When discussing repositories I would refer you to this answer which refers many other answers discussing repositories, their possible redundancy and possible mistakes when using them just to make your code testable. Generally each layer should be added only if there is real need for the layer - due to better separation of concerns.
The main advantage of POCOs is that those classes can be your DTOs, so if you've already got custom DTOs that you're using, POCO seems a bit redundant. However, there are some other advantages which may or may not have value to you, since you didn't mention unit testing as a requirement. If you plan to write unit tests, then POCO is still the way to go. You probably won't notice much difference between 4.0 POCO and 4.1 since you won't be using the code-first feature (disclaimer: I've only used 4.0 POCO, so I'm not intimately familiar with any minor differences between the two, but they seem to be more or less the same--basically I was already using POCO in 4.0 and haven't seen anything that's made me want to update everything to use 4.1).
Also, depending on whether you plan to unit-test this layer, there's still value in implementing the repository/unit of work patterns when using Entity Framework. It serves to abstract away the data access logic (the context), not the entities themselves, and allows you to do things like mocking your context in unit tests. What I do is copy the T4 template for my context and use it to create the interface, then edit the T4 template for the context and have it implement that interface and use IObjectSet<T> instead of ObjectSet<T>. So instead of:
public class MyEntitiesContext
{
public ObjectSet<MyClass> MyEntities
...
}
I end up with:
public interface IMyEntitiesContext
{
public IObjectSet<MyClass> MyEntities;
}
and
public class MyEntitiesContext : IMyEntitiesContext
{
public IObjectSet<MyClass> MyEntities
...
}
So I guess it really comes down to whether or not you plan to write unit tests for this layer. If you won't be doing anything that would require mocking out your context for testing, then the easiest thing to use would probably be 4.0 EntityObjects, since you aren't planning to pass your entities between layers and it would require the least effort to implement. If you plan to use mocking, then you'll probably want to use POCO and implement repository/unit of work.
I am working on a project using entity framework. Is it okay to use partial classes of the EF generated classes as the business layer. I am begining to think that this is how EF is intended to be used.
I have attempted to use a DTO pattern and soon realized that i am just creating a bunch of mapping classes that is duplicating my effort and also a cause for more maintenance work and an additional layer.
I want to use self-tracking-entities and pass the EF entities to all the layers. Please share your thoughts and ideas. Thanks
I had a look at using partial classes and found that exposing the database model up towards the UI layer would be restrictive.
For a few reasons:
The entity model created includes a deep relational object model which, depending on your schema, would get exposed to the UI layer (say the presenter of MVP or the ViewModel in MVVM).
The Business logic layer typically exposes operations that you can code against. If you see a save method on the BLL and look at the parameters needed to do the save and see a model that require the construction of other entities (cause of the relational nature the entity model) just to do the save, it is not keeping the operation simple.
If you have a bunch of web services then the extra data will need to be sent across for no apparent gain.
You can create more immutable DTO's for your operations parameters rather than encountering side effects cause the same instance was modified in some other part of the application.
If you do TDD and follow YAGNI then you will tend to have a structure specifically designed for the operation you are writing, which would be easier to construct tests against (not requiring to create other objects not realated to the test just because they are on the model). In this case you might have...
public class Order
{ ...
public Guid CustomerID { get; set; }
... }
Instead of using the Entity model generated by the EF which have references exposed...
public class Order
{ ...
public Customer Customer { get; set; }
... }
This way the id of the customer is only needed for an operation that takes an order. Why would you need to construct a Customer (and potentially other objects as well) for an operation that is concerned with taking orders?
If you are worried about the duplication and mapping, then have a look at Automapper
I would not do that, for the following reasons:
You loose the clear distinction between the data layer and the business layer
It makes the business layer more difficult to test
However, if you have some data model specific code, place that is a partial class to avoid it being lost when you regenerate the model.
I think partial class will be a good idea. If the model is regenerated then you will not loose the business logic in the partial classes.
As an alternative you can also look into EF4 Code only so that you don't need to generate your model from the database.
I would use partial classes. There is no such thing as data layer in DDD-ish code. There is a data tier and it resides on SQL Server. The application code should only contain business layer and some mappings which allow persisting business objects in the mentioned data tier.
Entity Framework is you data access code so you shouldn't built your own. In most cases the database schema would be modified because the model have changed, not the opposite.
That being said, I would discourage you to share your entities in all the layers. I value separation of UI and domain layer. I would use DTO to transfer data in and out of the domain. If I have the necessary freedom, I would even use CQRS pattern to get rid of mapping entities to DTO -- I would simply create a second EF data access project meant only for reading data for the UI. It would be built on top of the same database. You read data through read (anemic -- without business logic) model, but you modify it by issuing commands that are executed against real model implemented using EF and partial methods.
Does this answer your question?
I wouldn't do that. Try too keep the layers independent as possible. So a tiny change in your database schema will not affect all your layers.
Entities can be used for data layer but they should not.
If at all, provide interfaces to be used and let your entities implement them (on the partial file) the BL should not know the entities but the interfaces.