Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RavenDB dynamic objects

Tags:

c#

ravendb

I have code that looks something like this:

using (var session = DocumentStore.OpenSession())
{
    var dbItem = session.Load<dynamic>(item.Id);    
    if (dbItem is DynamicJsonObject)
    {
        dbItem["PropertyName"] = "new value";
    }
    session.SaveChanges();
}

What I can't figure out is how to update properties of the dbItem.
Does anyone know what to do? I have tried accessing the property name directly like this: dbItem.PropertyName I have also tried casting to ExpandoObject, IDictionary and more. But nothing seems to work.

like image 799
Quintonn Avatar asked Jun 13 '14 15:06

Quintonn


1 Answers

As of Raven 2.5, the support for dynamic objects seems to be mostly for the read side of things, and it's not that easy to set properties on an existing object because Raven.Abstractions.Linq.DynamicJsonObject, which inherits DynamicObject, only implements the read/invoke methods of the dynamic contract, like TryGetMember, TryGetIndex, and TryInvokeMember. but none of the items like TrySetMember.

However, if you cast to IDynamicJsonObject it provides access to the inner RavenJObject which you can manipulate.

This code sample should illustrate how:

using (var session = store.OpenSession())
{
    dynamic entity = new ExpandoObject();
    entity.Id = "DynamicObjects/1";
    entity.Hello = "World";
    session.Store(entity);
    session.SaveChanges();
}

using (var session = store.OpenSession())
{
    var json = session.Load<dynamic>("DynamicObjects/1") as IDynamicJsonObject;
    json.Inner["Name"] = "Lionel Ritchie";
    json.Inner["Hello"] = "Is it me you're looking for?";
    session.SaveChanges();
}

using (var session = store.OpenSession())
{
    dynamic loadedAgain = session.Load<dynamic>("DynamicObjects/1");
    Console.WriteLine("{0} says Hello, {1}", loadedAgain.Name, loadedAgain.Hello);
    // -> Lionel Ritchie says Hello, Is it me you're looking for?"
}
like image 181
David Boike Avatar answered Oct 02 '22 11:10

David Boike