Add remove data many-many relationship Entity Framework C#

Consider the example of a Users of an application having many roles like member, admin etc. The relationship in this case is many-many. The two entities in this case are Users and Roles. The many-many relationship is handled by a join table in the database say users_roles. If you import this join table in Entity Framework, it is automatically converted into a many-many association where the Users entity holds ICollection property of Roles entity and vice-versa.

public class User{
    public int id {get; set;}
    public string firstname {get; set;}
    public string lastname {get; set;}
    public ICollection<Role> roles {get; set;}
}

public class Role{
    public int id {get; set;}
    public string name {get; set;}
    public string resource_type { get; set; }
    public Nullable<int> resource_id { get; set; }
    public System.DateTime created_at { get; set; }
    public System.DateTime updated_at { get; set; }
    public ICollection<User> users {get; set;}
}

In the below example, the DBContext object as created as db. Create the Users model object and add roles for the User. This will automatically make an entry in the join table.

//Find existing user
var user = db.users.Find(userid);

//Remove existing role
DBMODELS.role role = db.roles.Include("users").Where(x => x.resource_id == moduleid && x.resource_type == "MyModule" && x.name == "admin").FirstOrDefault();
db.roles.Remove(role);
db.SaveChanges();

//Add new role.
DBMODELS.role newrole = new DBMODELS.role();
newrole.name = "super_admin";
newrole.resource_id = moduleid;
newrole.resource_type = "MyModule";
newrole.created_at = DateTime.UtcNow;
newrole.updated_at = DateTime.UtcNow;
db.roles.Add(newrole);
db.SaveChanges();

user.roles.Add(newrole);
db.SaveChanges();

Eager loading is achieved using the Include() method above.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.