Search code examples
c#asp.net-mvcentity-frameworkef-database-first

Entityframework why does coupling table get duplicated values?


I want to create new users in an application and assign roles to them. i have a coupling table between the user and role table. I manage to create a relationship between the tables but at the same time I am getting duplicates.

My model:

enter image description here

Problem:

Getting duplicates after the relationship is created. lets say I create a user with the role of "Support". The networkWebuserRoles gets the relationship BUT at the same time the NetworkWebRole gets a duplicate value.

context:

enter image description here

Code:

    var user = _dbContext.NetworkWebUser.FirstOrDefault(x => x.UserName == userName);

    user.NetworkWebRole.Add(new NetworkWebRole
    {
        RoleName = role.ToString()
    });

    _dbContext.SaveChanges();

creates a relationship between the role and user but It gives me duplicates.

Result :

enter image description here

EDIT:

To clarify:

When I run code above this happens:

NetworkWebUserRoles gets a new connection. BUT for some reason the NetworkWebRole also gets a new value so I get duplicates


Solution

  • You’re creating a new NetworkWebUserRole instead of linking to an existing record.

    I’d also recommend creating a uniqueness constraint on NetworkWebUserRole to prevent roles with duplicate names at the DB level.

    Example:

    user.NetworkWebRole.Add(role);
    

    This assumes that your role variable is of type NetworkWebRole. When you use the Add method of the user.NetworkWebRole, it will automatically create the entry in the NetworkWebUserRole table. If the role doesn't exist, e.g. calling new NetworkWebRole(), it'll insert into the coupling table and into the NetworkWebUserRoles table. So by passing the existing role object (presumably being tracked by your EF context), you're good to go.