Which variant of Entity Framework to use in WCF based enterprise app - entity-framework

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.

Related

Entity Framework - No Repository abstraction

In my project, I need to use EF and abstract the queries from the Presentation layer. Based from what I've been reading questions and answers all over the net, EF is built having repository pattern on it's DbSet and Unit of work on DbContext.
Repository pattern can easily do the requirement but I don't wanna repeat this implementation and now confused where should I initialize or access the DbContext. Should it be on the service layer?
MVC4 Api will be used for this project
One way I have seen this done in the past is to essentially remove the DbContext's dependency on a physical database by creating an interface for your context then make your data access calls from your Services Layer (Business Logic Layer).
There is however, a disadvantage in using this approach, which is the fact that your unit tests (which will be using a Fake implementation of your DbContext) will be using LINQ to Objects to run your queries whereas your concrete implementation will use LINQ to Entities which does not support all LINQ to Objects methods.
There's documentation on MSDN (http://msdn.microsoft.com/en-us/library/bb738550.aspx) which highlights these differences.
I also recommend reading this article (http://kearon.blogspot.com.au/2011/02/mocking-entity-framework-4-code-first.html) which demonstrates how to make DbContext unit testable by removing the inderlying dependency on a phyiscal database.
Hope this all helps!

Can Entity Framework generate the DAL code?

I know that entity framework has a database first approach. Now the question is whether it can generate the DAL (data access layer) code (not the models) for me.
When using a Object Relational Mapper (ORM), you don't typically have CRUD code in the traditional sense. Rather, it abstracts those operations into more object oriented operations.
For example, you don't "insert", you add the model class to the table, then save changes. The ORM automatically generates the SQL needed to make the Object model match the data model.
So my point is, your question displays a basic lack of understanding of how ORM's work and how they relate to data models. You should probably do a little reading.
I'm not sure what you mean specifically by "DAL code", as that's a rather ambiguous term. I would consider your Entity types part of the DAL.
When you use a model-first or database-first approach, the Entity Framework tools can auto-generate a context class from your model .edmx, which will inherit from ObjectContext. It's easy to customize the generated context class with T4 templates by finding one online that already generates from a .edmx, and modifying to your liking.
Code-first development uses the DbContext, which is not typically auto-generated. Please see this post on Scott Gu's blog for more details on this.

What are each of the template types intended usage, pros and cons?

I have not hardly touched EF4, but I've used Linq to sql quite a lot. I would like to start into one of the EF templates but I have no idea what situations make sense for each or what their intent was.
I have the following possibilities:
Data templates
ADO.NET Entity Data Model
Service-based Database (is this even related to EF?
Code templates (I am familiar with T4)
ADO.NET EntityObject Generator
ADO.NET Self-Tracking Entity Generator
Online Templates
ADO.NET C# POCO Entity Generator
I have no idea what situations make
sense for each or what their intent
was
Not meaning to sound rude, but did you have a look on MSDN/ASP.NET to find out? There is plenty of information around. And there is a lot to each of those templates, more than i can go into here. There is a MSDN page for each of these.
That being said, i'll give you a quick summary, so people who stumble here have some info.
ADO.NET Entity Data Model
This is the file you create to use Entity Framework as your ORM, and it is mandatory for using EF. You need this before you use any of the others. You can create your EDM with a number of different approaches, including database-first (generate from DB), code-first, model-first, etc.
Service-based Database
I have never heard of this term, and given i've been working with EF a lot lately (and reading), i doubt this will be related to EF.
ADO.NET EntityObject Generator
Generates classes for entities which inherit from the EntityObject class. Identical to the default EF code generator, except instead of putting output code into the Model.edmx.designer.cs (default) file, the code gets put into seperate files. I personally don't see any benefit in this template.
ADO.NET Self-Tracking Entity Generator
Generates classes for entities when you want to develop N-Tier applications (ie if you wanted to allow a WCF/Silverlight app to work with your model). Entities are setup to be 'trackable' by the EF Graph, in order to handle persistence operations from various applications.
ADO.NET C# POCO Entity Generator
My favourite. :) Generates classes for entities which inherit from nothing. They have no idea that they are being used for persistence. Use this for applications when you want persistence-ignorance, testability and loose-coupling of your domain/persistence layers.

Should i use partial classes as business layer when using entity framework?

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.

Entity Framework 4.0: Why Would One Use the Code Generated EntityObjects Over POCO Objects?

Aside from faster development time (Visual Studio 2010 beta 2 has no T4 templates for building POCO entity objects that I'm aware of), are there any advantages to using the traditional EntityObject entities that Entity Framework creates, by default? If Microsoft delivers a T4 template for building POCO objects, I'm trying to figure out why anybody would want to use the traditional method.
You're asking two questions at the same time, it seems. Code-only versus model-first and EntityObject parent type versus arbitrary parent type. You get designer support with model-first, regardless of parent type. Aside from designer support, you can also use precompiled views with model-first. That can significantly help performance.
Having EntityObject as a parent can be an advantage over so-called "POCOs" (which are usually proxy bases, not "plain" objects), because the runtime type of your entities are the exact type you expect, rather than a runtime-generated subtype.
Also, unlike other ORMs which have minimal to no LINQ support, the Entity Framework has rich LINQ support, allowing you to project onto real POCO types. Therefore, it is possible to build truly persistence-ignorant presentations without having to care about what the base type of your entities are. You are not stuck with whatever type comes out of the ORM blackbox.
EntityObject allows for private properties which are persisted to the database. Using proxy types requires that those properties are at least protected and must be virtual. Therefore, EntityObject may allow for better encapsulation.
I'm not trying to suggest, by the way, that there aren't advantages to using proxies; I'm just trying to answer your question about what the advantages of EntityObject are.
I think the only benefit is designer support. Can't find any other benefits in using non-poco entities.