Saving many to many relations.

Posts   
 
    
x3mka
User
Posts: 6
Joined: 23-Mar-2009
# Posted on: 23-Mar-2009 19:23:05   

Hi, guys.

I have a question about many to many relationships. Assume I have 2 tables in my database: Product and Category. I'm going to map my products to several categories, so I have an additional table ProductToCategory. How could the code look like for saving product data?

Suppose the interface for product editing contains of a simple Name textbox and check box list with categories.

Currently I have only 2 entities Product and Category mapped on my tables. But I cannot make out how to save product with categories assignments. Perhaps I should map an entity for ProductToCategory?

Version 2.5 Final. Self-servicing if possible.

Thank you in advance.

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 24-Mar-2009 04:26:31   

Hi there,

Adding a intermediat M:N relation should be done this way (quoting the manual):

How do I create a m:n relation between two entity objects?

The generated code will not save intermediate table entries in an m:n relation. Consider the two entities Department (DepartmentID (PK, int, identity), Description) and Employee (EmployeeID (PK, int, identity), Name). These two entities have an m:n relation, and this results in the third entity DepartmentEmployees (DepartmentID (PK), EmployeeID (PK)). To relate a new employee with an existing department follow the example below. It will add a new employee to the existing department with ID 1. You can of course also set the DepartmentID of the DepartmentEmployeesEntity by hand, avoiding the necessity to fetch the DepartmentEntity first.

// C#
DataAccessAdapter adapter = new DataAccessAdapter();
DepartmentEntity department = new DepartmentEntity(1);
adapter.FetchEntity(department);
EmployeeEntity newEmployee = new EmployeeEntity();
newEmployee.Name = "John Doe";
DepartmentEmployeesEntity departmentEmployees = new DepartmentEmployeesEntity();
departmentEmployees.Department = department;
departmentEmployees.Employee = employee;
// save recursively
adapter.SaveEntity(departmentEmployees);
David Elizondo | LLBLGen Support Team
x3mka
User
Posts: 6
Joined: 23-Mar-2009
# Posted on: 24-Mar-2009 04:53:19   

Thank you. I got the idea. Not very convenient but cleat and straightforward.