Can I delete an entity that is not in cache?

1k views Asked by At

I want to delete a record from the DB that hasn't been retrieved from a breeze query. The entity hasn't been retrieved so it's not in the cache, but I know the KEY of the record from another operation. Here's what I've tried:

create a new entity from the manager:

manager.createEntity(entityNames.book);

setting the ID :

bookToDelete().bookID(1);  // bookToDelete is a ko observable from step 1

updating the state:

bookToDelete().entityAspect.setDeleted(); 

When I save changes, this transaction is not included in the JSON

2

There are 2 answers

2
Jay Traband On BEST ANSWER

You almost have it. Calling entityAspect.setDeleted on an 'Added' entity moves it directly to a 'Detached' state, which in effect removes it from the EntityManager, and hence it cannot be saved. This is deliberate. It handles the case where you create an entity and later delete it. In this case, there is no entity to save.

So, in your case, you have to make the entity either 'Modified' or 'Unchanged' before you call entityAspect.setDeleted. You can do this by either calling entityAspect.setUnchanged or entityAspect.setModified before calling entityAspect.setDeleted or you can call entityAspect.acceptChanges.

Note that you will also have to insure that the 'clone' entity passes validation and if you have a concurrency field on the entity, you will need to set this appropriately as well.

UPDATE Dec 7th

You can create the book entity in the marked-for-delete state in a single step as shown:

var book = manager.createEntity(entityNames.book,
            { BookID: 1 },                  // use initializer to set the key
              breeze.EntityState.Deleted);  // creates the entity in the Deleted state

Be sure to initialize it with all other properties that are necessary for the entity to pass validation and optimistic concurrency checks on the server.

No problem if you don't have these checks. Not sure how you'd get those values without querying the server if you did have such checks.

0
mwill On

got it. cant delete entity while still in added state. I first setModified. then setdeleted. didnt see any side affects.