I'm using Entity Framework 4. I'm detaching the object graph using Serialization.
Getting the List, bind to a BindingSource, to the GridControl and deleting adding modify rows. Then go back and Attach the object graph back. How to ensure which rows are for deletion, which are modified, added rows is easy for EF to understand. I'm also thinking start learning about self tracking entities.
The Entities have Parent-Childs relationship. I need to Manage full parent deletion with childs or some child records. Books are not so useful to much talking about EF architecture and pointless examples.
My current difficulty on this project with SqlCe datasource is that i can't tell the ObjectContext which rows are for deletion because I am detaching from it.
Any help, points?
Thank you.
Check this thread. Because you mentioned BindingSource I assume you are doing some WinForm application. In that case definitely check STEs (Self Tracking Entities) because they will solve you a lot of problems. In your current solution you have to manually say object context exactly what you added, deleted and updated.
Related
Can anyone help me understand DataContext and DataSet ? I am leaning Entity Framework and I need to clear this concepts in my mind properly.
I tried to read in the book, read some articles but all the language there was so complex, can anyone explain me these terms using simple words with example?
Also if you can provide me the link of any video tutorials that could help me.
Thanks.
DbContext and DbSet are two classes that when you use EF code first approach, you can work with them.
Using Entity Framework you can simply define a mapping between your entities and tables.
In simple words, you can imagine DbContext as an In-Memory database, and DataSets as In-Memory tables(that initially are empty), you can imagine entity objects as rows of your tables in your database, too:
In your application you can query DbSets or do CUD(Creat,Update,Delete) operations on them instead direct access to your database and tables. You could execute multiple CRUD operations on DbSets, in simple database transaction, too.
I am using a DAL service to retrive data from the database.
Lets observe to simplest case where I retrieve one object from the database.
After retrieving that object I am doing some changes to its properties according to some business logic,
and than I want to update the object in the persistent database.
However, some other client (maybe even one I am not aware that exists) changed the state of the underline object in the database, and I identify this when I am trying to update.
What should I do in this case?
Should I throw an exception?
Should I try to update only the fields that I changed?
Should I lock that table for writing while I am performing bussiness logic based on the persistant data?
Guy
I think what you should do depends on what you are trying to achieve.
Your main options as i see it:
lock beforehand - main pros & cons - occupying the database until you commit, much more simple.
don't lock beforehand, merge in case someone else updated it - main disadvantage - merging can be very complex
I would go with the first one, but i would try to minimize the locking time (i.e i would figure out what's all the changes i want to do prior to locking the object).
Any way i don't think this is an exceptional case.. so i won't go with throwing exception.
This is very subjective and it depends on what exactly you are trying to.
Should I throw an exception?
You should if you are not expectig the update by other user. For instance, your software is trying to book a seat which has been already booked by somebody, you will throw say SeatAlreadyBookedException and handle that appropriately by logging or showing proper message
Should I try to update only the fields that I changed?
You can do that if you have not used the existing state to make an update or you want your changes to be final changes overriding any changes already done by other users. For instance, if want to update a new date for the dead-line for a project.
Should I lock that table for writing while I am performing bussiness
logic based on the persistant data?
Locking a table will affect the overall throughput. Your application logic should take of these transactions and maintan the data integrity.
Hi i am developing an App in WPF who will have paginated records (i am doing the pagination myself depending on the filters or in the number of records per page the user wants to be shown).
So i have never worked serious with DataGrids and what i am asking is, what is the best approach and better politic when we work with a DataGrid to update the Table in the DB?
We detect the row who have been changed, or we update the whole Table in the DB, what is the better way?
Because the user can change one row, and then other, and imagine the user changes 50 rows, the App will have to connect 50 Times with the DB?
Unit of work is probably the most common infrastructure solution to this problem, basically it stores the changes applied to the data and when ready executes them in a transaction to the database. There are many ORM mappers like Entity Framework or nHibernate that already do this for you, so id start there.
EDIT
See this example implementation as it sounds like from your comments yould need to write your own version, but basically you build a list of inserts, updates, deletes that should happen and execute them all in a trasaction, first inserts, then updates, then deletes but Id recommend you look at an ORM like the ones i described above they already have this as a feature.
I am in the middle of development of a WPF application that is using Entity Framework (.NET 3.5). It accesses the entities in several places throughout. I am worried about consistency throughout the application in regard to the entities. Should I be instancing separate contexts in my different views, or should I (and is a a good way to do this) instance a single context that can be accessed globally?
For instance, my entity model has three sections, Shipments (with child packages and further child contents), Companies/Contacts (with child addresses and telephones), and disk specs. The Shipments and EditShipment views access the DiskSpecs, and the OptionsView manages the DiskSpecs (Create, Edit, Delete). If I edit a DiskSpec, I have to have something in the ShipmentsView to retrieve the latest specs if I have separate contexts right?
If it is safe to have one overall context from which the rest of the app retrieves it's objects, then I imagine that is the way to go. If so, where would that instance be put? I am using VB.NET, but I can translate from C# pretty good. Any help would be appreciated.
I just don't want one of those applications where the user has to hit reload a dozen times in different parts of the app to get the new data.
Update:
OK so I have changed my app as follows:
All contexts are created in Using Blocks to dispose of them after they are no longer needed.
When loaded, all entities are detatched from context before it is disposed.
A new property in the MainViewModel (ContextUpdated) raises an event that all of the other ViewModels subscribe to which runs that ViewModels RefreshEntities method.
After implementing this, I started getting errors saying that an entity can only be referenced by one ChangeTracker at a time. Since I could not figure out which context was still referencing the entity (shouldn't be any context right?) I cast the object as IEntityWithChangeTracker, and set SetChangeTracker to nothing (Null).
This has let to the current problem:
When I Null the changeTracker on the Entity, and then attach it to a context, it loses it's changed state and does not get updated to the database. However if I do not null the change tracker, I can't attach. I have my own change tracking code, so that is not a problem.
My new question is, how are you supposed to do this. A good example Entity query and entity save code snipped would go a long way, cause I am beating my head in trying to get what I once thought was a simple transaction to work.
A global static context is rarely the right answer. Consider what happens if the database is reset during the execution of this application - your SQL connection is gone and all subsequent requests using the static context will fail.
Recommend you find a way to have a much shorter lifetime for your entity context - open it, do some work, dispose of it, ...
As far as putting your different objects in the same EDMX, that's almost certainly the right answer if they have any relationships between objects you'll want them in the same EDMX.
As for reloading - the user should never have to do this. Behind the scenes you can open a new context, reloading the current version of the object from the database, applying the changes they made in the UI annd then saving it back.
You might want to look at detached entities also, and beware of optimistic concurrency exceptions when you try to save changes and someone else has changed the same object in the database.
Good question, Cory. Thumb up from me.
Entity Framework gives you a free choice - you can either instanciate multiple contexts or have just one, static. It will work well in both cases and yes, both solutions are safe. The only valuable advice I can give you is: experiment with both, measure performance, delays etc and choose best one for you. It's fun, believe me :)
If this is going to be a really massive application with tons of concurrent connections I would advise using one static context or one static, core context and just few additional ones just to support the main one. But, as I wrote just few lines above - it's up to your requirements which solution is better for you.
I especially liked this part of your question:
I just don't want one of those
applications where the user has to hit
reload a dozen times in different
parts of the app to get the new data.
WPF is a really, really powerful tool and basically times when users have to press buttons to refresh data are gone forever. WPF gives you a really wide range of asynchronous, multithreading tools such as Dispatcher class or Background worker to gently refresh desired data in the background. This is really great, because not only you don't have to worry about pressing various buttons, but also background threads don't block UI, so data is refreshed transparently from user's point of view.
WPF together with Entity Framework are really worth the effort of learning - please feel free to ask if you have any further concerns.
Let's say theres a Teacher object and that Teachers holds a list of Courses objects.
The courses for the Teacher can change. Some get added, some get deleted.
What's the best approach to update this changes in the database.
1. Right after every change, update the database. e.g.: A course get added, immediately add that into the database as well .
2. After all changes are made to the entity/object Teacher (courses are added, courses are deleted), only then update the database with all the changes.
3. Others ??
I can see for both 1 and 2 advantages and disadvantages.
For 1: I don't know how good it is when data models have direct access to the database.
For 2: The algorithm its more complex because you have to compare the information in the data models with information in the database all at once.
Thank you
Take a look at some of the ORM tools available for your language or platform. An object's representation of an entity in the database can always get out-of-sync. For example, if a user changed a certain property, and a database update was attempted but for whatever reasons that update failed. Now these two items are not synchronized.
It may also depend on the frequency of updates to your database. If you don't expect massive activity in terms of writes to the database, triggering instant database updates on any property change may be an option.
Otherwise, you may include a dirty flag in your object to indicate when it goes out of sync with the database. Object changes could be updated as they happen, or when a event is triggered such as when the user decides to save their progress, or periodically, say every x minutes.
Different languages and frameworks implement these model objects differently. In Rails, a model object is subclasses from ActiveRecord and knows how to persist itself into a database. In Java, you would rarely mix domain objects with the way they're persisted. That's usually taken care of by an ORM framework or custom DAO objects.
I found out about Hibernate. It's exactly what i need and it's simple.