Many to many mapping and insert, update operation

Thread is closed for posting
4 posts, 0 answers
  1. Peenty
    Peenty avatar
    1 posts
    Member since:
    Dec 2010

    Posted 15 Feb 2012 Link to this post

    I have many to many mapping on basis tables:

    Id int, PK
    Name varchar(50), not null

    Id int, PK
    Name varchar(50), not null

    RoleId int, PK, FK to Roles.Id
    PrivilegeId int, PK, FK to Privileges.Id

    I have existing privileges (in table Privileges) and I'd like to insert a new Role with selected privileges.
    I try someting like this:

    Role role = new Role();
    role.Name = "Role ABC";
    role.Privileges.Add(new Privilege { Id = 1, Name = "Privilege 1" });
    role.Privileges.Add(new Privilege { Id = 3, Name = "Privilege 3" });
    After this I get error Telerik.OpenAccess.Exceptions.DuplicateKeyException because it tries to insert
    new privileges (to Privileges table) instead of to insert new row to RolePrivileges table.
  2. Damyan Bogoev
    Damyan Bogoev avatar
    581 posts

    Posted 16 Feb 2012 Link to this post

    Hello Krzysztof,

    You should slightly modify this code snippet in the following way:

    Role role = new Role();
    role.Name = "Role ABC";
    Privilege firstPrivilege = dbContext.Privileges.FirstOrDefault(x => x.Id == 1);
    Privilege secondPrivilege = dbContext.Privileges.FirstOrDefault(x => x.Id == 3);

    Hope that helps.

    Damyan Bogoev
    the Telerik team
    Want to use Telerik OpenAccess with SQL Azure? Download the trial version today. 
  3. KFS
    KFS avatar
    4 posts
    Member since:
    Feb 2014

    Posted 18 Jul 2016 in reply to Damyan Bogoev Link to this post

    How can that managed if the select and insert operation managed by different DB context ?

    Privilege firstPrivilege =  dbContext1.CreateDetachedCopy( dbContext1.Privileges.FirstOrDefault(x => x.Id ==  1));
    Role role = new Role();
    role.Name = "Role ABC";

    This cause create new privilege and insert the new privilege Id in table RolePrivileges.


  4. Boris Georgiev
    Boris Georgiev avatar
    190 posts

    Posted 21 Jul 2016 Link to this post


    I was not able to reproduce this behavior. The observed and default behavior in this scenario is that only new role will be created in the database and one record will be added in the Join table between the id of the new role and the id of the detached privilege. To achieve this behavior you should add the new created role to the navigation property of the detached privilege and Attach the role to the context, for that you should use AttachCopy method instead Add method.

    For your convenience I attached a sample which demonstrates the workflow.

    I hope that helps.

    Boris Georgiev
    Telerik by Progress
    Check out the latest announcement about Telerik Data Access vNext as a powerful framework able to solve core development problems.
Back to Top