Search code examples
c#neo4jclient

Error with explicit conversion when using CollectAs<>


Right I have a really simple problem, but I cannot for the life of me think of the really simple answer to go with it. This code is supposed to return a single 'Person', with a collection of languages and countries.

return client.Cypher
            .Match("(person:Person)")
            .Where((Person person) => person.Email == username)
            .OptionalMatch("(person)-[:SPEAKS]-(language:Language)")
            .OptionalMatch("(person)-[:CURRENT_LOCATION]-(country:Country)"
            .Return((person, language, country) => new ProfileObject
            {
                Person = person.As<Person>(),
                Language = language.CollectAs<Language>(),
                Country = country.CollectAs<Country>()
            }).Results.ToList();

It looks right to me, but it isn't, on build I get this error, which I understand but cannot solve.

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<Neo4jClient.Node<Graph.Country>>' to 'Graph.Country'. An explicit conversion exists (are you missing a cast?)

The Language class looks like this

public class Language
{
    public string Name { get; set; }
}

And the ProfileObject class looks like this:

public class ProfileObject
{
    public Person Person { get; set; }
    public Language Language { get; set; }
    public Country Country { get; set; }
}

I am really stuck, please help.


Solution

  • CollectAs returns a set of nodes.

    You need to change your ProfileObject to:

    public class ProfileObject
    {
        public Person Person { get; set; }
        public IEnumerable<Node<Language>> Language { get; set; }
        public IEnumerable<Node<Country>> Country { get; set; }
    }
    

    In a forthcoming update to the package, the Node<T> wrapper has been removed from the signature, so it will just be:

    public class ProfileObject
    {
        public Person Person { get; set; }
        public IEnumerable<Language> Language { get; set; }
        public IEnumerable<Country> Country { get; set; }
    }
    

    If you want to get that cleaner signature now, check out the pre-release packages on NuGet (https://www.nuget.org/packages/Neo4jClient/1.1.0-Tx00009).