Export/Import entities which were created server-side - breeze

If you create entity client-side through EntityManager.createEntity(), when exporting, breeze generates tempKeys and assigns them to newly created entities.
But some entities are created server-side, but not saved(just created with new operator). Breezejs client is making a query. EntityState of fetched entities is Unchanged. PrimaryKey Id=0, it was just created, but not saved to db.
When you make exportEntities on manager it does not generate tempKeys, and entity Id remains zero. I tried to manually set EntityState to Added on that entities before exporting, but still tempKeys are not generated.
Any ideas how to properly export not-saved entity which came from server-side?

I think Breeze only creates a new temp key when the entity is attached to the EntityManager with state 'Added'. So try this:
entityManager.detachEntity(entity);
entityManager.attachEntity(entity, breeze.EntityState.Added);
That should cause a new temp key to be generated.

Related

Using breeze.js I only want to send updated properties for a non-cached entity

I have a scenario where I know the primary key of an entity (retrieved from an unrelated source), and I want to update just 1 property (db column). I have NOT already retrieved the entity from the database. If possible I would like to not have to make this extra round trip.
I create the entity using manager.createEntity.
I update one of the properties.
Then set the entityAspect to setModified();
When saving changes, all the properties that were not updated are set to their default values, and the generated SQL UPDATE statement attempts to update all mapped columns.
Is there a way to tell breeze to only generate SQL for specific properties/columns?
thanks
As you discovered, the properties of the originalValuesMap guide the Breeze server's ContextProvider as it prepares the save request. This is documented in the ContextProvider topic.
In your example, you call setModified after you've changed the property. All that does is change the EntityState; it doesn't create an entry in the client entity's entityAspect.originalValuesMap ... therefore the originalValuesMap sent to the server is empty.
I'm a little surprised that the EFContextProvider.SaveChanges prepared an EF update of the entire entity. I would have guessed that it simply ignored the entity all together. I'm making a mental note to investigate that myself. Not saying the behavior is "right" or "wrong".
You do not have to manipulate the originalValuesMap to achieve your goal. Just change the sequence. Try this:
var foo = manager.createEntity('Foo', {
id = targetId
}, breeze.EntityState.Unchanged); // create as if freshly queried
foo.bar = 'new value'; // also sets 'originalValues' and changes the EntityState
manager.saveChanges(); // etc.
Let us know if that does the trick.

Breeze - removing element from cache

I am keeping local entities in breeze cache, how can i delete them from the cache with out going to the server?
in the documentation it states
Deleting an entity
You delete an entity by changing its EntityState to “Deleted” like this:
1
someEntity.entityAspect.setDeleted(); // mark for deletion
setDeleted does not destroy the object locally nor does it remove the entity from the database. The entity simply remains in cache in its new “Deleted” state … as changed and added entities do. A successful save does delete the entity from the database and remove it from cache.
You can do this by detaching the entity from entity manager by calling manager's detachEntity method :
manager.detachEntity(entity);
The detached entity will eventually be garbage collected.
Refer to Breeze-Inside Entity
You can do
entity.setDeleted();
and then call
saveChanges method.
if you want to save it in DB.
if not want to go to server
manager.detachEntity(nameofYourEntity);

Entity Framework complaining about required fields when saveChanges even if valid data are setted

I'm using Entity Framework (DbContext with database first) with MVC. When user save from a form, I have a condition in the controller that send the entity to the update of insert method depending of some internal flag of mine.
When sending entity to the update method, I flag it to modified using context.Entry(myEntity).State = EntityState.Modified;, I call saveChanges() and everything work well.
When sending the entity to the insert method, I flag it to added using context.Entry(myEntity).State = EntityState.Added; but when calling saveChanges() I receive error about 2 fields that are required...
The problem is that thoses 2 fields are not empty and they effectively contain valid data just before saving... I have even try to force new values to thoses 2 fields just before saving but same error.
It may be usefull to mention that I'm using Devart DotConnect For PostgreSQL as db provider.
Any idea how to debug this problem?
EDIT:
Here is the error:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
When looking for this EntityValidationErrors I receive the 2 following specific errors:
The flg_actif field is required
The user_creation field is required
As mentionned before, those fields are filled with data just before saving so I don't understand what is happening.
I'm using EF v4.0.30319 (system.data.entity=> v4.0 and EntityFramework=> v4.4)
EDIT2:
Just to clarify a little bit more: The entity I'm trying to insert already exist in database. The form show the data of this database row. When saving, I decide if I update the row (this work well) but sometime, I need to insert the edited row as a new register instead of updating it to keep an history of the change in database.
Could you verify if the EntityKey property is set or null on the items you are trying to save?
If it already has a key, the context is already aware of the item, and you should use Attach instead of setting the state to added manually.
EDIT: To summarise the point from below. It looks like what you are doing is inserting a new copy of a row already associated with a context. That is almost certainly your problem. Try creating a fresh object based on your original row (i.e. copy the variable values or use a copy constructor), then add that new object.
Additionally, you should not need to set the state manually on a newly added object. You are trying to force the state here because the context doesn't see that item as a new one.

EF 4.1 Code First Detaching Entity

I am trying to add an entity to the DB. Once I have added it, I want to detach it, so I can manipulate the object safely without making any changes to the DB. After calling context.SaveChanges() I do the following to detach the entity:
// save
context.Stories.Add(story);
// attach tags. They already exists in the database
foreach(var tag in story.Tags)
context.Entry(tag).State = System.Data.EntityState.Unchanged;
context.SaveChanges();
context.Entry(story).State = System.Data.EntityState.Detached;
However, changing the entity state to DETACHED will remove all related entities associated with the my entity. Is there a way to stop this ?
If I don't detach the entity, all my changes are sent to the DB next time I call context.SaveChanges()
Thanks!!
There is no way. It is limitation of EF. Your options are:
Not using the same context for another save (single context instance = single save)
Retrieve the entity from database again using another context instance which will not be used for saving
Create deep clone of your entity and use the clonned one (deep clone is done by serialization and immediate deserialization = your entity graph must be serializable)
I think there are two ways to approach this problem:
Purist: retrieving entities from a DbContext and modifying them without saving is a misuse of the tools and the architecture. Use a DTO instead.
Pragmatic: you can use AsNoTracking() to retrieve an entity graph that will not be tracked by the context for changes.

Querying from a DataServiceContext

I have an oData generated DataServiceContext and I am successfully adding entities to it. I need to add a whole load of entities and then commit them in a single SaveChanges with the Batch option set at the end. This is all fine, until I come to query it before the save changes.
Outline is:
Create a new entity
Add it to the DataServiceContext
Run a query on the context looking for the item I have just added - IT IS NOT FOUND
My previous work with EF4 would suggest that if this was an Entity Context, all would be fine, but because this is a Service Context I cannot query for an entity that has been added but not saved to the service.
Is this the case?
DataServiceContext is basically just a small helper. Running any query against it will run the query on the server directly, the client will not try to fixup the data in any way. Since you're changes haven't made it to the server yet (SaveChanges was not called yet), the query will not return the newly added entities.
If you really need to list the entities you've added before SaveChanges, you could use the DataServiceContext.Entities collection which will return EntityDescriptor for all entities tracked by the context. You can list those added by looking for those with state Added.

Resources