This project has moved and is read-only. For the latest updates, please go here.

Any way to avoid resetting context when doing get?

Jul 9, 2014 at 6:42 PM
Edited Jul 10, 2014 at 4:48 PM
I would like to delete a set of entities in a table by enumerating them one by one and take advantage of batch write capability for deletion.

If I use Linq2Dynamo like in the sample below, only the last entity in the list gets deleted. I tried to trace it and found that the context is cleaned up upon any read (get). Is there a good reason for such behaviour?
var ctx = new DataContext(...);

var t = ctx.GetTable<MyEntity>();

var keys = new List<Guid> { guid1, guid2 }; 
var allEntities = keys.Select(id => t.Where(e => e.Id == id));

allEntities.Select(e => { t.RemoveOnSubmit(e); return true; }).ToList();

Jul 10, 2014 at 3:02 PM
Edited Jul 10, 2014 at 3:02 PM
Yes, the context (not the context, but the table, actually) is cleared on each query. That's the way all datacontexts work, at least on .Net platform, as far as I know. This is the common semantics.

The reason is that the DataTable<TEntity> is usually supposed to be databound to some kind of DataGrid, or other visual control. The user changes query options => the table is requeried => the DataGrid is refreshed with new data.

I'm not sure, what you were trying to do (your code is not compilable), but if you need to delete a couple of entities by their ID's, I would propose the following:
var t = ctx.GetTable<MyEntity>();

var keys = new List<Guid> { guid1, guid2 };
foreach (var en in t.Where(en => keys.Contains(en.Id)))

Or just use the natural Amazon.DynamoDBv2.DocumentModel.DocumentBatchWrite tool for the same effect.
Jul 10, 2014 at 3:37 PM
Thanks for the reply - my intention was to use multiple Get requests (for the lack of BatchGet) and for each item in the list remove them from the DB and write update in a single batch.

It seems like what you are suggesting works as a Scan operation, which I wanted to avoid.

I am trying to avoid Dynamo DocumentModel. I solved my problem by first doing multiple get requests using ToList() to enumerate through all queries and then feeding resulting list to RemoveOnSubmit().

I still don't quite understand why this behavior is the default. At least I would like to be able to control it/disable it when necessary.
Jul 10, 2014 at 4:11 PM
OK, then why not just:
foreach (var en in keys.Select(k => new MyEntity {Id = k}))

This internally leads to a DocumentBatchWrite with two delete operations.
Marked as answer by AgentKay on 7/10/2014 at 8:48 AM
Jul 10, 2014 at 4:47 PM
Yes, this would work when you have primary keys as in my example.

In more generic case, though, an entity needs to be looked up based on secondary key, and each read would still invalidate the context, which was quite unexpected to me.

Anyway, thanks for the help!