Dynamic RavenDB Objects

I have some 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(); } 

I cannot figure out how to update the dbItem properties.
Does anyone know what to do? I tried to access the property name as follows: dbItem.PropertyName I also tried casting for ExpandoObject, IDictionary and others. But nothing works.

+6
source share
1 answer

As with Raven 2.5, support for dynamic objects seems to mostly relate to the read side, and it's not so easy to set properties for an existing object because Raven.Abstractions.Linq.DynamicJsonObject , which inherits DynamicObject , only implements read / call dynamic contract methods such as TryGetMember , TryGetIndex and TryInvokeMember . but none of the elements like TrySetMember .

However, if you added to IDynamicJsonObject , it provides access to an internal RavenJObject that you can manipulate.

This code example 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?" } 
+3
source

Source: https://habr.com/ru/post/970803/


All Articles