Raskolnikov
Raskolnikov

Reputation: 3999

Many to many relationship insert and update

Many to many relationship. I am using EntityFramework 6.1.2 For example relationship is between Users and Roles.

I need to support next scenario

Add new user without role, and than later add new roles for that user. But when I add new user than some roles are new and some roles already exist in db, so I dont want to duplicate roles i db.

When I am adding new role I am not sure if this role exist (do i need update or add?).

I implemented scenario when I add users and roles all together. But I want to add role later, also add user later with existing roles.

What is good practice for scenarios like this? Do you have any example?

Upvotes: 0

Views: 52

Answers (1)

P. Wenger
P. Wenger

Reputation: 541

You can check if there are already existing roles. Then just add the roles which are new.

//your roles which will be assigned to the user
var roles = new List<Roles>();

//get the ids of the existing roles
var existingRoleIds = context.Roles.Select(r => r.Id).ToList();

//filter the existing roles out
var rolesToAdd = (from r in roles
                where existingRoleIds.Contains(r.Id) == false
                select r).ToList();

//add the new roles
context.Roles.AddRange(rolesToAdd);
context.SaveChanges();

Upvotes: 2

Related Questions