How to extend Entities data context's ObjectSet - c#

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

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.

Are Entity Framework Models Reusable?

How reusable are the results of using EF?
Currently, I use stored procedures for 100% of my data access. The main reason I may be looking to do things differently for my newest project is for maintainability: adding an attribute to a table means manually altering dozens of stored procedures. If I understand EF correctly, I should be able to add an attribute to an Entity in my EF model, and then ask EF to update my CRUD methods for me. awesome.
However, there is one thing holding me back: reusability. I like that I can make the SP's for a given database once, and be done with them; I can make 12 applications that all use that database and getting that data will be as easy as calling the correct SP.
Will the same be true if I switch to a more EF-centric approach?
Can I import an Existing EF Data Model and have it work without too much trouble?
Can I make it so that I alter the Data Model once, and that change is felt across all applications?
Ad1. You can easily reuse complex EF queries if you follow the Repository pattern. Repositories are where you encapsulate your data access and, yes, repositories are easily reused between different modules/applications.
(not that you can't reuse code without Repositories! Repositories are just a common way of doing it for data access layer)
Ad2. I am not sure what you mean by "import existing EF model" (import where?) but usually EF models are straightforward and can be reused
Ad3. Just have your model in a separate assembly.
A real benefit to using EF is getting away from stored procedures.
The problem that exists with using stored procedures for all your data access is that you are forced to put business logic into your data layer.
Check out Should the data access layer contain business logic? While its not true in every case, generally keeping your business logic in your business layer gives you better separation of concerns.
I have an EF project that I use as the data layer for several applications. This allows me to change it once and have all the other projects get the benefits. Granted, sometimes supporting code needs to be changed in these other projects, but you'd have that same problem in a stored procedure model as well.
Any N-tier design would solve this problem by simply creating a class (in a class library) that understands how to access the data by using entity framework. Then any applications that want to access the data uses the class library, configure a connection string in the app.config or web.config and you're done.

Should I use inheritance in Entity Framework or is there a better approach?

I have various objects that I would like to track in an application. The objects are computers, cameras, switches, routers etc. I want the various objects to inherit from an object called Device since they will all have some properties in common (i.e. IP Address, MAC Address, etc.) I like to create the objects using the designer (Model First) but I do not like the difficulty in updating the database from the model. Basically, I do not like to have to drop the database and recreate it, especially once I start populating the database. The other approach that I experimented with was creating the database using SSMS in SQL Server, but then when I create the POCOs from the database the entities do not inherit from each other. What is a good approach for my situation ?
I want the various objects to inherit from an object called Device since they will all have some properties in common (i.e. IP Address, MAC Address, etc.)
You are essentially talking about which inheritance pattern you are going to use in EF; or how the model maps to your database tables. There are 3 main types of inheritance patterns in EF (see Inheritance Mapping: A Walkthrough Guide for Beginners):
Table-per-Hierarchy
Table-per-Type
Table-per-Concrete Type
Each has pros and cons (such as performance). But, you should also consider that this model is a model that relates to the database, and in larger projects you might then create a second layer to work with for business logic. DDD talks about persistence models and domain models. Again, your choices here are weighing up initial speed of development and scalability and performance later on.
I like to create the objects using the designer (Model First) but I do not like the difficulty in updating the database from the model.
There are 4, and only 4 development strategies for EF (see Entity Framework Development Workflows):
Model First
Code First (new database)
Database First
Code-first (existing database)
I do not like to have to drop the database and recreate it, especially once I start populating the database
Code First is really very, very good at this:
Seeding in Code First allows you to populate databases with test or live data depending on where you are deploying to.
Migrations allow you to do non-destructive updates to the database, and migrate data in a fully testable, utterly reliable fashion for live deployment.
Doing this with Model First is, unfortunately, just harder. The only real solution I know is to generate a new database, and use a SQL compare (with data compare) tool to generate the data in the new database.
Choosing a pattern and a strategy
Each strategy has pros and cons, and each inheritance pattern is better used with particular development strategies. The trade offs are really your own to judge, for example you might have to use database-first if you have en existing database you inherited, or you may be happier using the EF designer so would use model-first.
Model First (by that I mean using the EF designer to define your model) uses the TPT strategy by default. See EF Designer TPT Inheritance. If you want TPH, then you can use Model-first (see EF Designer TPH Inheritance), but you have extra work to do; Code First is a better fit for TPH. TPC is even harder using Model First, and Code First is really the best (only viable) option for that in EF 5.
when I create the POCOs from the database the entities do not inherit from each other
It is good to remember that the model deals with classes; the database deals with storage in tables. When generating a model from your database it is hard for EF to work out what the TPH or TPC inheritance should be. All it can do is create a "best guess" at your model based on the table assocations. You have to help it out after the model is generated by renaming properties, changing associations or applying inheritance. There really is no other way to do this. Updates to the database may also therefore require more work on the model.
Your best approach
That is, unfortunately, down to opinion. However if your primary requirements are:
You want TPH or TPC (or mixed strategies)
You don't want to drop your database when you issue updates to the model
then the best match for these technical requirements is Code First development, with migrations and seeding.
The downside of Code First is having to write your own POCOs, and learning the data annotation attributes. However, keep in mind:
writing POCOs is not so different from writing a database table (and once you are used to it is is just as quick)
Code First is a lot more usable with automated testing (e.g. with DI and/or IoC to test without the database involved), so can have benefits later on
If you are going to do a lot of EDMX manipulation with database first, or a lot of work whenever you drop and update your database using model first, then you are just putting in time and effort in other places instead of in writing POCOs

What's the difference between DbContext and ObjectContext

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.

Categories

Resources