Search code examples
c#neo4jneo4jclient

Linking All Nodes of two types by ids


With the following code I create 2 types of nodes. In Neo4J

  public async Task CreateData()
  {
     AddNodesAsync<Companies>(myCompanies);
     AddNodesAsync<Employess>(myEmployes);
  }

  public Task AddNodesAsync<T>(List<T> nodes)
    {
        return client
            .Cypher
            .Create("(n:" + typeof(T).Name + " {nodes})")
            .WithParams(new {nodes})
            .ExecuteWithoutResultsAsync();
    }

Each Employe has a company id. Now I want to relate all of them when the id of the company of the employee matches the one on the company.

With the following code I can link one employe to one company

await client.Cypher
            .Match("(company:Company)", "(employee:Employee)")
            .Where((employee: company) => employee.ComanyId == company.Id)                       
            .Create("employee-[:BELONGS_TO]->company")
            .ExecuteWithoutResultsAsync();

but how can I tell that it should link all employed by this id ref to their correspondand company?


Solution

  • I assume there is a typo somewhere, this is the code I use which generates the links as you say it should.

    Using these as the POCOs:

    public class Company {
        public int Id { get; set; }
    }
    
    public class Employee {
        public int Id { get; set;}
        public int CompanyId { get; set;}
    }
    

    Adding them:

    var companies = new List<Company> { new Company { Id = 1 }, new Company {  Id = 2 } };
    var employees = new List<Employee>
    {
        new Employee{ Id=1, CompanyId =1 },
        new Employee{ Id=2, CompanyId =1 },
        new Employee{ Id=3, CompanyId =1 },
        new Employee{ Id=4, CompanyId =2 },
        new Employee{ Id=5, CompanyId =2 },
    };
    
    await AddNodesAsync(companies);
    await AddNodesAsync(employees);
    

    This next bit generates the graph as you expect, with the relationships all created correctly.

    await client.Cypher
        .Match("(company:Company)","(employee:Employee)")
        .Where((Company company, Employee employee) => employee.CompanyId == company.Id)
        .Create("(employee)-[:BELONGS_TO]->(company)")
        .ExecuteWithoutResults();