---
title: "Many-to-many insert with Entity Framework"  
description: "Many-to-many insert with Entity Framework"  
author: "Anonymous User"  
published: 2013-09-28  
updated: 2013-09-28  
canonical: https://www.mindstick.com/forum/1548/many-to-many-insert-with-entity-framework  
category: "ado.net"  
tags: ["ado.net"]  
reading_time: 2 minutes  

---

# Many-to-many insert with Entity Framework

I'm two [entities](https://www.mindstick.com/blog/250/html-character-entities) in my Data Model, for example User and Role, both having the ID field as [primary key](https://www.mindstick.com/blog/214/primary-key). There's a many-to-many [relationship](https://yourviews.mindstick.com/view/80819/live-in-relationship-protecting-the-right-to-live-together) between them. In the [database](https://www.mindstick.com/articles/12226/use-of-database-in-sencha-extjs-and-insert-record-from-user-form-using-ajax) there are three tables: Users, Roles and UsersRoles junction table.

I'm trying to add a new user to the Users table:

```
using(var myContext = new MyContext)
{
   var user = new User() { ... };
   user.Roles.Add(new Role() { ID = 1 });
}
```

\

The same role can be already be used by another Users, so, when I try to add a new User with the same Role, I become Primary key violation as EF tries to add a new record to the Roles table.

Is there any way to tell the [Entity Framework](https://www.mindstick.com/articles/1566/crud-operations-using-entity-framework-code-first-approach) not to add a new record to the Roles table, when such role [already exists](https://www.mindstick.com/forum/34205/emailid-already-exists), but only update the Users and UserRoles tables? EF [version](https://www.mindstick.com/articles/12845/things-to-remember-while-migrating-odoo-to-a-better-version) 1.0

Thanks in advance.

## Replies

### Reply by Anonymous User

Hey Jay!

If the role [already](https://yourviews.mindstick.com/view/88453/the-hidden-ways-ai-is-already-controlling-your-daily-life) exists in the DB you must EF tell that by attaching the role to the context:

```
using(var myContext = new MyContext)
{
    var role1 = new Role() { ID = 1 };
    myContext.Roles.Attach(role1);
    var user = new User() { ... };
    user.Roles.Add(role1);
    myContext.Users.AddObject(user);
    myContext.SaveChanges();
}
```

\

(I hope that this also works the same way in EF 1.)


---

Original Source: https://www.mindstick.com/forum/1548/many-to-many-insert-with-entity-framework

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
