Click here to Skip to main content
15,558,870 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I am inserting data from database first method.

I have 3 tables.
1. UserMaster 2. roles 3. UserRoles.

When i create edmx it create the model like below:

C#
public partial class UserRole
    {
        public int UserRoleID { get; set; }

        public virtual Role Role { get; set; }
        public virtual User User { get; set; }

    }


C#
public partial class User
    {
        public User()
        {
            this.UserRoles = new HashSet<UserRole>();
        }

        public string UserID { get; set; }
        public string EmailAddress { get; set; }
        public Nullable<System.DateTime> CreatedDate { get; set; }
        public string CreatedBy { get; set; }

        public virtual ICollection<UserRole> UserRoles { get; set; }
    }



C#
public partial class Role
    {
        public Role()
        {
            this.UserRoles = new HashSet<UserRole>();
        }

        public int RoleID { get; set; }
        public string RoleName { get; set; }

        public virtual ICollection<UserRole> UserRoles { get; set; }
    }



Now when i insert data bt this:
C#
Role obj_role = new Role();
                    var roles = ent.Roles.Where(m => m.RoleID == model.RoleID);
                    foreach (var item in roles)
                    {
                        obj_role.RoleID = item.RoleID;
                        obj_role.RoleName = item.RoleName;
                    }


                    User obj_user = new User();
                    obj_user.UserID = model.LoginName;
                    obj_user.EmailAddress = model.EmailAddress;

                    UserRole obj_UserRole = new UserRole();
                    obj_UserRole.User = obj_user;
                    obj_UserRole.Role = obj_role;

                    obj_user.UserRoles.Add(obj_UserRole);
                    obj_role.UserRoles.Add(obj_UserRole);
                    ent.Users.Add(obj_user);
                    
                    ent.SaveChanges();


But every time it create new record in Roles table.
please suggest..
Posted

1 solution

Please check if role already exists in db or not, then do your fucntionaly
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900