Insert into bridge table entity framework

6.3k Views Asked by At

Hi guys,
I'm learning to climb with EF ,I do have basic understanding of CRUD with EF ,but now I have a table which have a navigation property (Which I suspect is the bridge table) ,so I need to add value into the bridge table ,I think I can do it with navigational property.

Problem Explained:
Original partial DB Diagram enter image description here

Partial EF Model Diagram
enter image description here

Code I Wrote:

   protected void BtnAddUser_Click(object sender, EventArgs e)
    {
        DBEntities entities = new DBEntities();
        var usr = new User();
        //I thought I would add an Roles object into usr.UserRoles.Add(usrRoles);
        //but UserRoles have only two fields ,RoleTypeId and UserId 
        //var usrRoles = new Roles() 
        //{Id=0,RoleDescription="dfdfdf",RoleType="WebSite Admin"}; 

        usr.UserName = TxtbxUserName.Text;
        usr.Password = TxtBxPassword.Text;
        usr.Email = TxtbxEmail.Text;
        usr.CreateDate = DateTime.Now;
        usr.LastActivityDate = DateTime.Now;
        usr.IsEnabled = true;

        //What to Add in the .Add method
        usr.UserRoles.Add(

        entities.User.AddObject(usr);
        int result = entities.SaveChanges();
        LblMsg.Text = result == 1 ? "User created successfully." : "An error occured    ,please try later.";

        entities.Dispose();
    }

Update (What I have tried so far):
I fetch "Website Admin" role from roles table and put it into ObjectContext.UserRoles.Add(UserRoleWebsiteAdmin); So that what I did in the code,

        //Fetch WebsiteAdmin from Roles
        var userRole = from usrRole in entities.Roles
                       where usrRole.Id == 1
                       select usrRole;

        usr.UserName = TxtbxUserName.Text;
        //same old code of usr.Property = someTextBox
        //I have tried to type cast it LinqtoEntities result into Roles
        usr.UserRoles.Add((Roles)userRole);

Exception generated
enter image description here

P.S: Let me know if you need more clarification.

2

There are 2 best solutions below

1
On BEST ANSWER

Maybe you can use using http://msdn.microsoft.com/en-us/library/yh598w02.aspx and object initializer http://msdn.microsoft.com/en-us/library/bb384062.aspx for better readability so:

using(DBEntities entities = new DBEntities())
{
       //Make user object
       var user = new User{
            UserName = TxtbxUserName.Text,
            Password = TxtBxPassword.Text,
            Email = TxtbxEmail.Text,
            CreateDate = DateTime.Now,
            LastActivityDate = DateTime.Now,
            IsEnabled = true
        };

       //Fetch type of Role from Roles table
       var userRole = entities.Roles.Where(x=>x.usrRole.Id ==1).Single();
       user.UserRoles.Add(userRole);

       entities.User.AddObject(user);
       int result = entities.SaveChanges();
       LblMsg.Text = result == 2 ? "User created succesfully." : "An error occured ,please try later.";
}

Regards

0
On

Well thanks guys... Here what I have done and it works,

       DBEntities entities = new DBEntities();
       //Make user object
       var usr = new User();
       //Fetch type of Role from Roles table
       var userRole = (from usrRole in entities.Roles
                       where usrRole.Id == 1
                       select usrRole).Single();
        //copy user related info from textboxes
        usr.UserName = TxtbxUserName.Text;
        usr.Password = TxtBxPassword.Text;
        usr.Email = TxtbxEmail.Text;
        usr.CreateDate = DateTime.Now;
        usr.LastActivityDate = DateTime.Now;
        usr.IsEnabled = true;


        usr.UserRoles.Add(userRole as Roles);

        entities.User.AddObject(usr);
        int result = entities.SaveChanges();
        LblMsg.Text = result == 2 ? "User created succesfully." : "An error occured ,please try later.";

        entities.Dispose();