Since MSDN says about DbContext:
A DbContext instance represents a combination of the Unit Of Work and
Repository patterns such that it can be used to query from a database
and group together changes that will then be written back to the store
as a unit. DbContext is conceptually similar to ObjectContext.
Is it not redundant to implement these two (Unit of Work & Repository) when using EF5+?
Can somebody shed more light on this subject?
I intend to build an MVC based application using SQL server and after reading a lot about data access techniques with unit testability, I am kind of lost with the above info!
That depends on the complexity of your project and its requirements. For instance, these two questions might help your decision making:
Will you use any other data sources besides EF that must work along it?
How likely it is that you swap EF for a different ORM or data source in the future?
If you can't foresee changes or you don't need to work with more than just EF then it's probably not worth the trouble.
I would create a Generic repository so you can mock it in your tests more easily than mocking Entity Framework's context directly. But, yes, EF 5+ does implement these patterns as MSDN states.
It's a layer of abstraction. The repository pattern is a collection of objects and a thing to get a collection of objects. Entity Framework knows HOW to get that collection of objects, the repository does not know HOW.
Entity Framework has a lot features that you potentially loose by wrapping it in a repository or a thinner service. If you practise TDD coding against your own classes is often more comfortable than mocking third-party code.
Ayende has a blog post about this.
Related
Currently i am refactoring test for my context methods to not need a real database anymore. I use Ef Core.
So i read through the Microsoft documentation how to test context methods. I found the documentation for EF6 testing first and read the one for EfCore after.
Here are the links:
Ef Core Testing
Ef 6 Testing
What i found interesting is that there are different best practices for EF6 and EF Core.
For EF6 Microsoft advises to use Mocking contexts with Moq or writing own test doubles.
So both times mocking the context.
For EF Core Microsoft advises to use Sqlite or the built in InMemory database.
Mocking the context with Moq seems pretty reasonably for me. I just want to test the functionality of the methods. I have to do integration test anyways afterwards. Why is it not in the recommended ways for EF Core anymore?
And more generally what are the advantages or problems with the different methods?
Take a closer look at the following quote from the same article...
SQLite in-memory mode allows you to write efficient tests against a provider that behaves like a relational database.
This provides you with constant and non changing test data but also the relational database problems and behaviors. It's much closer to the actual real life scenarios.
Mocking on the other hand provides you with an implementation where you can change the relational to any other model, thus it is much more versatile.
Since EF is for db and you are making tests for EF, then it makes perfect sense to go with the first option. More often than not you will not even need to test trivial operations like genetic repositories, e.t.c.
Make sure that when testing on a higher level (classes that consume repositories and such) you use mocking, as you want to mock interfaces which have no and should not have any coupling with the concrete implementations.
In the sense of application layers, I have a hard time figuring out, how to place Entity Frameworks DbContext. It seems to me that it aims to replace the repository layer, but on the other hand it doesn't really work like a more basic repository, which is implemented via an interface, making it easy to swap later.
So I found a lot of good posts on the service and repository layer (e.g. this post), but it doesn't seem to answer where Entity Framework fits in this pattern.
Should I add a repository layer on top of Entity Framework or should I just use DbContext in place of a repository, in my services?
You need to ask yourself why would you want to abstract away your data-access layer.
The answer would typically be:
Unit Testing
Replacing the layer with another DB / persistence technology
Many are arguing that the 2nd argument is utterly false because:
Replacing that layer would usually have a much wider effect on your application than just configuring another implementation
It rarely happens and doesn't worth the effort
All in all, I tend to agree that testability should be your main concern and in the case of EntityFramework you can:
Use EF Core with its built-in InMemory provider
Use EF 6 and mock all the methods and DbSets in your context (by marking them as virtual).
And, to answer your question title: Yes. DbContext is already acting as a repository.
EF isn't a layer, it's a data access technology.
EF calls should be written inside a repository, which serves as an abstraction to the service layer so that the service layer doesn't care if the data are stored in a database or somewhere else.
I had a conceptual question about EF.
I am pretty new to the idea of an ORM in general, so I wanted to get some clarification on somethings:
I have an existing database, and I want to convert the data I am pulling from that data into objects that my application can interact with as objects, rather than just data.
An ORM will accomplish that, correct?
In EF can I create methods specific to my objects? For instance, can I make it so my application can call something like employee.ViewDetails() Where employee is an object?
If so, is there a simple tutorial you could recommend?
Is EF portable between applications? Meaning, is it easy to build an EF structure and then port it to multiple applications?
I can just do that by referencing it from different solutions, no?
Thanks for all the help
Before Answering your Question let me give you short brief about Entity Framework
Using the Entity Framework to write data-oriented applications provides the following benefits:
Reduced development time: the framework provides the core data access capabilities so developers can concentrate on application logic.
Developers can work in terms of a more application-centric object model, including types with inheritance, complex members, and relationships. In .NET Framework 4, the Entity Framework also supports Persistence Ignorance through Plain Old CLR Objects (POCO) entities.
Applications are freed from hard-coded dependencies on a particular data engine or storage schema by supporting a conceptual model that is independent of the physical/storage model.
Mappings between the object model and the storage-specific schema can change without changing the application code.
Language-Integrated Query support (called LINQ to Entities) provides IntelliSense and compile-time syntax validation for writing queries against a conceptual model.
Going Back to your first Question
Yes
Entity framework is useful in three scenarios.
1- First, if you already have existing database or you want to design your database ahead of other parts of the application. (Which is your current case)
2- Second, you want to focus on your domain classes and then create the database from your domain classes.
3- Third, you want to design your database schema on the visual designer and then create the database and classes.
2) in EF can I create methods specific to my objects? For instance, can I make it so my application can call something like employee.ViewDetails() where an employee is an object? If so, is there a simple tutorial you could recommend?
Yes Sure Take a look on this:
- https://msdn.microsoft.com/en-us/library/dd456847.aspx
- http://www.asp.net/mvc/overview/older-versions-1/models-data/creating-model-classes-with-the-entity-framework-cs
3) Is EF portable between applications? Meaning, is it easy to build an EF structure and then port it to multiple applications? I can just do that by referencing it from different solutions?
you might need to Implementing the Repository Patterns
Have a look at this Amazing tutorial
http://blog.gauffin.org/2013/01/repository-pattern-done-right/
http://rycole.com/2014/01/25/entity-framework-repository-pattern.html
Hope this helps!
Wish you the best :)
Blubberbo,
There are various ways to work with EF, they are Code First, Model First and Database first.
More information can be found in the below SO post.
Code-first vs Model/Database-first
1) You can use LINQ to SQL or LINQ Objects in context with an ORM like EF to interact with Objects.
2) If you would like methods specific to specific types, then you might want to take a look at writing extension methods for specific types.
More information here
https://msdn.microsoft.com/en-us/library/bb311042.aspx
3) To make it portable, you might want to build abstractions around it, like for example you might want to write repository classes to separate the DB layer that uses EF and the layer that calls it(a.k.a the repository layer).
More info can be found here
http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
Hope that helps,
Praveen Raju
So at my job I was pointed to http://www.codeproject.com/Articles/990492/RESTful-Day-sharp-Enterprise-Level-Application#_Toc418969121 and was told to learn these patterns and implement them in my solution.
What confused me was that these things were before entity framework 6 and from what I understood, Unity of Work is used to optimize database performance by grouping queries together. Since EF6 has already these optimizations, should I still implement these layers? I get that the layerness helps with modularization and switching of data source. Does that mean that EF6 is too complex to implement with these patterns and should ADO.Net be used directly or something like that?
EDIT: I've noticed that this added layer allows usage of mock data sources. Not sure how useful this is because of the need to add another layer of apstraction
"Unit of Work is used to optimize database performance by grouping queries together." - This is not correct. Unit of Work is there to collect related operations together into a single transaction which is then committed or rolled back as a whole. It tracks changes made to objects so that required database operations can be deduced automatically and performed on your behalf.
When you work with Entity Framework, you use it to create DbContext from model. That class is both the Repository and Unit of Work, so you don't have to do anything special. Things only become more complicated than that when your project becomes so large that DbContext becomes more of a burden.
Repository is used to abstract your application from datasource, but since EntityFramework implements this pattern by itself and gives you a possibility to change data source seamlessly, there is no neccesity to add one more layer of abstraction.
You will just limit EF possibilities, while creating something like GenericRepository<T>. And nevertheless you won't be able to replace EF by another library with no changes to your code, even if you implement such a layer. (Some queries written for EF will fail for NHibernate, for example).
Just don't use DbContext everywhere in your application (inside UI code at least), use it by your data access layer (services with business dependent methods or something in that way).
Even for scenarios, where some cloud data storage is used (which EF won't be able to handle seamlessly), there is no neccessity for that layer, it's better to introduce separate classes and use them explicitly, because you cannot fit db and cloud interaction into one abstraction, it will start leaking at some point.
Entity Framework is a UnitOfWork/Repository pattern itself. If you need to abstract yourself from EF, then you could implement a layer on top of EF with your own UoW/Rep pattern.
This is good if you want to replace EF at some point in your proyect.
The cons? I think that building a UoW on top of EF gives you a redundant architecture and you will end up writing more code for something that maybe will never change.
In my current proyect, the main structure is very common, with a Data layer (with a sublayer for the Entities) for EF, Logic layer (where I put all the Business Logic) and the View layer (It can be web, or whatever). With that structure I directly invoke EF in the Logic layer.
I'm pretty new to IoC, Dependency Injection and Unit Testing. I'm starting a new pet project and I'm trying to do it right.
I was planning to use the Repository pattern to mediate with the data. The objects that I was going to return from the repositories were going to be objects collected from a Linq to entities data context (EF4).
I'm reading in "Dependency Injection" from Mark Seeman that doing it, makes an important dependency and will definitely complicate the testing (that's what he's using POCO objects in a Library Project).
I'm not understanding why. Although the objects are created by a linq to entities context, I can create them simply calling the constructor as they were normal objects. So I assume that is possible to create fake repositories that deviler these objects to the caller.
I'm also concerned about the automatic generation of POCO classes, which is not very easy.
Can somebody bring some light? Are POCO objects trully necessary for a decoupled and testable project?
**EDIT: Thanks to Yuck I understand that it's better to avoid autogeneration with templates, which brings me to a design question. If I come from a big legacy database wich his tables are assuming a variety of responsabilities (doesn't fit well with the concept of a class with a single responsability), what's the best way to deal with that?
Delete the database is not an option ;-)
No, they're not necessary it just makes things easier, cleaner.
The POCO library won't have any knowledge that it's being used by Entity Framework. This allows it to be used in other ways - in place of a view model, for instance. It also allows you to use the same project on both sides of a WCF service which eliminates the need to create data transfer objects (DTO).
Just two examples from personal experience but there are surely more. In general the less a particular object or piece of code knows about who is using it or how it's being used will make it more adaptable and generic for other situations.
You also mention automatic generation of POCO classes. I don't recommend doing this. Were you planning to generate the class definitions from your database structure?
I was planning to use the Repository pattern to mediate with the data.
The objects that I was going to return from the repositories were
going to be objects collected from a Linq to entities data context
(EF4).
The default classes (not the POCOs) EF generates contain proxies for lazy loading and are tied at the hip to Entity Framework. That means any other class that wants to use those classes will have to reference the required EF assemblies.
This is the dependency Mark Seeman is talking about. Since you are now dependent on these non-abstract types, which in turn are dependent on EF, you cannot simply change the implementation of your repository to something different (i.e. just using your own persistence store) without addressing this change in the class that depend on these types.
If you are truly only interested in the public properties of the EF generated types then you can have the partial classes generated by EF implement a base interface. Put all the properties you need in that base interface and pass the dependency in as the base interface - now you only depend on the base interface and not EF anymore.