What's the difference between DbContext and ObjectContext - c#

From MSDN:
Represents a combination of the Unit-Of-Work and Repository patterns and enables you to query a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.
I though DbContext only handle the connection to the DB and the number of threads working against the DB.
Now I understand it contains the tracking mechanism? I thought this was in the ObjectContext.
So what is (in plain English) the difference between them?

DbContext is a lightweight version of the ObjectContext class, which is laid almost right on top of ObjectContext (there is even a way to get to the ObjectContext from just the DbContext). It's also a lot easier to use, IMO, and makes CRUD operations a sinch.
For better information, who better to look to than Julie Lerman for more info on the differences, as was brought into EF 4.1.

the DbContext is a smaller API exposing the most commonly used
features of the ObjectContext. In some cases, those features are mirrored in the DbContext
API. In other cases, the Entity Framework team has simplified more complex coding
by providing us with methods like Find or properties like DbSet.Local. But there’s
a big API lurking underneath that you may still need access to. For example, you might
want to work directly with the MetadataWorkspace to write generic code against classes
because that API can read the model more efficiently than reflection. Additionally, the
MetadataWorkspace is able to provide more information about the metadata than you
can discover with reflection, for example, for Key properties. Or you might want to
take advantage of a database-specific function that is exposed through Entity SQL,
which you can’t access from LINQ to Entities.
Or you may already have an application
written using the ObjectContext and you want to leverage the DbContext in future updates
without replacing all of the ObjectContext code.(Reference from Programming DbContext)

Object Context:
1.It support compiled query
2.It support self tracking of entities
3.It available for entity frame work 4.0 and below version
4.It is not thread safe.
5.It is best for DB first and model first approach.
Database Context:
1.It does not support compiled query
2.It support not self tracking of entities
3.It available for entity frame work 4.1 and above version
4.It is thread safe for static and share member(public).
5.It is best for DB first and model first approach and code first approach.

Related

entity framework clarification about model objects and their methods

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

Do I neet Unity of Work and Repository patterns when working with Entity Framework?

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.

Shall, I implement Repository, Unit of Work for EF6?

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.

Entity Framework 4 - Embed ObjectContext reference within generated Entities

I am new to Entity Framework 4.0, using it with C#, and currently experimenting with its features.
What I noticed is that, like with most similar ORMs, it relies on an Context object to deal with the data-manipulation and CRUD statements generation done on the generated entities.
This means that if I want to save the changes back to the database, I always need to be able to have access to a reference to the ObjectContext that has instanciated the entities.
It is fine and all if the context has been created in an accessable scope (same method, for example), but what if I pass an entity or and entity set to a method and want this method to save the changes? It looks like the only easy way is to pass the ObjectContext along with the parameters.
Another solution would be placing the ObjectContext in some sort of global variable.
Needless to say, I find styling and maintainability issues to both of these approaches.
In short, the best way I can imagine is getting a reference to the ObjectContext from the entity or entity set.
I know that it isn't possible by default.
I have found a method showing adding an extension method to get the ObjectContext from the entity. However, it only works for entities with relationships and calling this method is expensive according to the author.
I was thinking about maybe modifying the T4 template to add a Context property to all my entities and fill it automatically on entities' instanciation.
I have already modified T4 template once to have Entity Framework enforce Max Length on my generated classes (by following Julie Lerman's Programming Entity Framework 4 book).
I can't say I really enjoy the T4 syntax so far, but if that's the best/only way, so be it...
Has anyone already done so and what would be the best way to handle this and willing to share his T4 template or explain what are the best partial methods or events to hook into to get this done?
Is there any major downside in using such an approach?
I am thinking that having so many references to the ObjectContext may hinder/delay its ability to be recollected by the GC if some of my entities remain in scope but I actually have no use anymore for the ObjectContext.
Many thanks.
If you need to pass object context as parameter together with your entities you are doing something wrong.
Usually context is needed only in well defined layer. All classes from this layer which requires context to their logic can receive the context through some specialized class - context provider (it can also be called service locator). Context provider will hold current context instance in some storage - you can create your own or you can store it per thread, per http request, etc.
If they need more then one context instance in your classes you can modify your provider to work also as factory.
Another common approach is combined with dependency injection. You will pass the context to your classes through the constructor (or property) and you will have some bootstraper code which will do all necessary initialization for you (create required instances and pass all dependencies into them). Again you can pass a context or a factory. This is usually used together with IoC containers which will do the plumbing for you.
Once you have this infrastructure prepared you can pass your entity to the any initialized class from that layer and it will have the context available.

How to extend Entities data context's ObjectSet

I want to implement a sort of preview mechanism for my application. I have few different models that can be edited. On the edit page's I would like to provide a preview button that would put the edited model into session.
I am thinking maybe I could extend the ObjectSet properties to have it run queries through my in session objects on top of the regular objects in the database. I dont know if that is actually possible, but can anyone think of a way to make something like this happen?
It sounds like you would need a Repository / Unit of work layer that is independent of where the data is coming from, in the "Session" case it could come from in-memory objects stored in the current session, in the regular case from your DB Entity context. You could then pass in the actual data store handling (in memory or DB) as a dependency.
There are many samples around that do work with EF, mostly for the sake of unit testing w/o having to touch the DB:
Testability and Entity Framework 4.0
Creating a Generic Entity Framework 4.0 Repository
Entity Framework 4 POCO, Repository and Specification Pattern

Categories

Resources