Reputation: 43
I'm using NLOG for logging with the JsonLayout and want to store these logs in RavenDB 4.0. Basically I'm trying to store raw json into ravendb using the RavenDB .NET client.
I had a working solution in RavenDB 3.5: using a class inheriting from "RavenJObject" but this functionality was depricated in 4.0.
I got it working by deserializing the json into a dynamic and storing the dynamic object. But this stores the document in a meaningless "JObjects" collection. It also seems overhead to convert json to dynamic and back to json again.
var obj = JsonConvert.DeserializeObject<dynamic>(jsonString);
session.Store(obj);
I know it's possible using the UI (raven studio). But i can't find a way doing it using the .Net client.
I think it's maybe possible using the http api, doing a post with the raw json. But I haven't found any documentation about this.
Who can help me out? Any advice is appreciated!
Upvotes: 4
Views: 700
Reputation: 1615
Here you have code sample which allows you to operate on generic type and assigns collection properly:
[Fact]
public void RawJson()
{
using (var store = GetDocumentStore())
{
using (var session = store.OpenSession())
{
var json = "{ 'Name' : 'John', '@metadata' : { '@collection': 'Users' } }";
var blittableJson = ParseJson(session.Advanced.Context, json);
var command = new PutDocumentCommand("users/1", null, blittableJson);
session.Advanced.RequestExecutor.Execute(command, session.Advanced.Context);
}
using (var session = store.OpenSession())
{
var user = session.Load<User>("users/1");
Assert.Equal("John", user.Name);
}
}
}
public BlittableJsonReaderObject ParseJson(JsonOperationContext context, string json)
{
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
return context.ReadForMemory(stream, "json");
}
}
public class User
{
public string Id { get; set; }
public string Name { get; set; }
}
Upvotes: 5