Johan de Klerk
Johan de Klerk

Reputation: 2535

Relationships in entity framework

Hi I'm using Entity framework 5 and mvc4 and struggling with the entity framework relationships

I have a User, Role and UserRole table SQL Table The model is created in Entity framework

enter image description here

Here is the code I use to save the User and the Role but this doesnt work The User and Role object properties is set before being passed to this method

public void saveNewUser(User u, Role r)
{
    using (FormValueEntities db = new FormValueEntities())
    {
        u.Roles.Add(r);
        r.Users.Add(u);
        db.SaveChanges();
    }
}

How do I create a new user and set the Role at the same time?

Upvotes: 1

Views: 320

Answers (4)

testCoder
testCoder

Reputation: 7385

You can try to use Membership api:

                    const string adminRole = "Administrator";
                    const string adminUserName = "Admin";
                    WebSecurity.CreateUserAndAccount(adminUserName, "123456", null, false);
                    Roles.CreateRole(adminRole);
                    Roles.AddUsersToRole(new string[] { adminUserName }, adminRole);

Upvotes: 0

Justin Harvey
Justin Harvey

Reputation: 14682

I think it might be because the User and Role are not attached to the context you are creating. So you need to do this sort of thing:

User newUser = new User(){ ... Set proprties ...};

db.Users.Add(newUser);

newUser.Roles.Add(r);

db.SaveChanges(); 

Note that you don't need to add the link in both directions explicitly.

Upvotes: 1

Đức Bùi
Đức Bùi

Reputation: 527

First you have to update your Entity Framework.

And code :

public void saveNewUser(User u, Role r)
{
    using (FormValueEntities db = new FormValueEntities())
    {
        db.Role.Add(r);
        db.User.Add(u);
        db.SaveChanges();
    }
}

Upvotes: 0

Konstantin Dinev
Konstantin Dinev

Reputation: 34915

Don't forget to include the UserRole table in your entity. You can simply drag and drop it in the design view.

Upvotes: 0

Related Questions