Boas Enkler
Boas Enkler

Reputation: 12557

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?

Upvotes: 0

Views: 37

Answers (1)

Charlotte Skardon
Charlotte Skardon

Reputation: 6270

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();

Upvotes: 1

Related Questions