I have a third party service from which I’m getting a large collection of data and I want to store that information in my local database. Suppose I have 3 tables in my database User, Role and UserRole.
- User table contains the following fields – UserId(PK), UserName.
- Role table contains the following fields – RoleId(PK), RoleName.
- UserRole table contains the following fields – UserId(FK),RoleId(FK).
So there is a Many To Many relationship between User and Role table.
When I try to save the following records to database its generating duplicate records in Role table.
using (CFAContext context = new CFAContext())
{
context.Users.Add(new User { UserName = "User 1", Roles = new List<Role> { new Role { RoleName = "Role 1" }, new Role { RoleName = "Role 2" }, new Role { RoleName = "Role 3" } } });
context.Users.Add(new User { UserName = "User 2", Roles = new List<Role> { new Role { RoleName = "Role 1" }, new Role { RoleName = "Role 2" } } });
context.Users.Add(new User { UserName = "User 3", Roles = new List<Role> { new Role { RoleName = "Role 1" }, new Role { RoleName = "Role 4" } } });
context.SaveChanges();
}
How can I insert this list to database(User and Role) without any duplicate records in User and Role table ?
I guess the
RoleIdfields are unique identifiers, thus for each role you have added, you will get a new record in the database with differentRoleIdfields as you are creating a newRoleinstance.If you change your code to the following it will work;