Saving many to many related entities

Posts   
 
    
methodman
User
Posts: 194
Joined: 24-Aug-2009
# Posted on: 09-Mar-2011 15:03:34   

I have two entities in a many to many relationship

I'd like to save one entity and several related entities.

I have this code

IEnumerable<ProjectMembersEntity> projectMembers = GetProjectMembers();

var project = new ProjectsEntity();

 foreach (var entity in projectMembers )
{
      project.ProjectMembersCollectionViaProjectsMembersProject.Add(entity);
}

adapter.SaveEntity(project);

but there's an error when adding ProjectMembers entities to the ProjectMembersCollectionViaProjectsMembersProjectcollection which says the collection is only readonly.

How Am I supposed to save the entities in one go ?

methodman
User
Posts: 194
Joined: 24-Aug-2009
# Posted on: 09-Mar-2011 15:18:59   

I'm using the 3.1 runtime.

Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 09-Mar-2011 15:27:41   

Example from the docs:

DepartmentEmployees newDepEmp = new DepartmentEmployees();
newDepEmp.Employee = employee;
newDepEmp.Department = department;

// the 3 entities are now linked. We can now save recursively any of the three (doesn't matter) 
// to save the relation in the database.
adapter.SaveEntity(employee, false, true);