Bryandh
Bryandh

Reputation: 529

Linq query to get data from a specific RavenDB collection not working as expected

So I'm using a RavenDB database which contains two different collections to store Picture objects as documents. The first collection is named Pictures, the second is named DeletedPictures.

In the application this is for, the user can delete a picture of themselves. The deleted Picture object will then be put in the second collection DeletedPictures. I'm doing this by changing the RavenDB document metadata:

Session.Advanced.GetMetadataFor(picture)[Constants.RavenEntityName] = "DeletedPictures";

I'm running into problems when making queries to retrieve the documents from the DeletedPictures collection.

Currently I'm using two functions that utilise Linq queries to retrieve Picture documents, one for retrieving all deleted pictures;

    public IEnumerable<Picture> RetrieveAllDeleted()
    {
        var allDeletedPictures = Session.Query<Picture>()
                                        .AsEnumerable()
                                        .Where(p => Session.Advanced.GetMetadataFor(p)
                                            .Value<string>("Raven-Entity-Name") == "DeletedPictures");
        return allDeletedPictures;
    }

And one for retrieving all deleted pictures from a specific user;

    public IEnumerable<Picture> RetrieveAllDeletedOfUser(int userId)
    {
        var allDeletedPicturesOfUser = Session.Query<Picture>()
                                                .Where(p => p.Owner == userId)
                                                .AsEnumerable()
                                                .Where(p => Session.Advanced.GetMetadataFor(p)
                                                    .Value<string>("Raven-Entity-Name") == "DeletedPictures");
        return allDeletedPicturesOfUser;
    }

Found out that I have to use .AsEnumerable() in my Linq chain otherwise I will get the error:

Cannot understand how to translate value Session.Advanced.GetMetadataFor(p).Value("Raven-Entity-Name")

So let's say the Pictures collection contains 2 documents and the DeletedPictures collection contains 6 documents (pictures with the same user as owner). The first function returns an empty list, this is wrong because it should return 6 documents. (All the deleted pictures)
The second function returns a list with 6 items, so this one seems to be working fine.

What is wrong with my query(ies)?

Upvotes: 0

Views: 696

Answers (2)

Thomas Freudenberg
Thomas Freudenberg

Reputation: 5078

To query metadata, you need a Lucene query:

session
    .Advanced.LuceneQuery<Picture>()
    .WhereEquals("@metadata.Raven-Entity-Name", "DeletedPictures");

Upvotes: 0

Ayende Rahien
Ayende Rahien

Reputation: 22956

Changing the collection of an object isn't supported. You need to delete and recreate it (even if the same id is used).

Upvotes: 1

Related Questions