0

I'm not sure if this is possible, but I'm trying to use the C# Azure Table API to update a property in table storage by creating a brand new entity and merging it:

// Create an object that only specifies the property to update
// (null properties are not updated)
var itemToUpdate = new TableEntity("PartitionKey", "RowKey");
itemToUpdate.DateLastAccessedUtc = DateTime.Now;
// can't do this!          
//itemToUpdate.DateCreatedUtc = null;

// Attach to the item, update it, and save the changes
_dataContext.AttachTo(_dataContext.TableName, itemToUpdate, "*");
_dataContext.UpdateObject(itemToUpdate);
_dataContext.SaveChanges();

Basically, I want to update the last accessed date without updating the created date, but since DateTimes cannot be null, I can't do it. Is it possible to do this without making two calls to the table? Since this will be called frequently, I don't want to retrieve the object before updating it if I can avoid it.

2
  • Can you set DateCreated back to itself? Commented Mar 14, 2011 at 22:52
  • Since I'm trying to update the object without retrieving it first from table storage, I don't have a value to set it to. When I create a new TableEntity, the DateCreated field just gets set to the default DateTime value. So, unfortunately, I can't :( Commented Mar 14, 2011 at 23:26

1 Answer 1

1

While it is true that a DateTime itself can't be null, if you use a Nullable<DateTime> (or DateTime? if you prefer) instead then you are able to set that date to null (and the Storage Client Library understands what to do with Nullable<> types. This may not make sense for the other places you're using this object though.

If using a nullable type doesn't make sense for that you could try this alternate idea (I'm not sure how sensible this is, but I think it will do what you want). Create a new class TableEntityJustLastAccessed which has the usual PartitionKey/RowKey/Timestamp properties plus just the DateLastAccessedUtc property that you want to update.

In your update code, rather than creating a TableEntity, create a TableEntityJustLastAccessed with the same PartitionKey/RowKey and save that. Because by default the storage client library merges changes rather than override the whole object, it should update just the property you care about.

Sign up to request clarification or add additional context in comments.

1 Comment

These are both good solutions. Since the second solution makes it more difficult to extend the property list, I ended up going with using Nullable types, which worked like a charm. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.