Search code examples
.netentity-framework-4poco

Insert Many to Many Scenario in EF 4.0 with POCO Classes


I have a database schema like follows:

User 1 ---- * UserRole *----1 Role

I have a POCO User and Role classes as follows:

public class User
{
    public virtual Int64 Id { get; set; }
    public string FullName { get; set; }

    public virtual List<Role> Roles { get; set; }
}

public class Role
{

    public virtual Int64 Id { get; set; }
    public string Name { get; set; }
    public virtual List<User> Users { get; set; }
}

I have a business component classes and a data access classes to to handle business logic and the data access.

I wanted to add Roles to a selected user and and the code is like follows:

In Business Component:

    public void AssignRoles(User user, string[] roleIds)
    {
        user.Roles.Clear();
        foreach (string roleId in roleIds)
        {
            Role role = new RolesDataAccess().SelectRoleById(int.Parse(roleId));
            if (role != null)
            {
                user.Roles.Add(role);
            }
        }
        this.SaveUser(user);
    }

    public User SaveUser(User user)
    {   
        if (user.Id == 0)
        {
            return dataAccess.Create(user);
        }
        else
        {
            return dataAccess.Update(user);
        }
    }

In Data Access:

    public User Update(User user)
    {
        EntityKey key = null;
        object original = null;

        using (DocsFlowContext ctx = new DocsFlowContext())
        {
            key = ctx.CreateEntityKey(User.EntitySetName, user);
            if (ctx.TryGetObjectByKey(key, out original))
            {
                ctx.ApplyCurrentValues(key.EntitySetName, user);
            }
            ctx.SaveChanges();
        }

        return user;
    }

This code runs without any errors but it doesn't insert any data to my UserRole table. Any one have an idea about this?


Solution

  •     public class UserRole
        { 
        public virtual User User {get; set;}
        public virtual Role Role {get;set;} 
        }
    public class User
    {
    ...
    public virtual List<UserRole> UserRoles { get; set;}
    }
    
    public class Role
    {
    ...
    public virtual List<UserRole> RoleUsers { get; set;}
    }
    

    or

    public class User
    {
    ...
    public virtual List<Role> Roles { get; set;}
    public virtual Role Role { get; set;}
    }
    
    public class Role
    {
    public virtual List<User> Users { get; set;}
    public virtual User User { get; set;}
    }
    

    first solutions it is look like better, you should add DbSet UserRoles to your DbContext

    It has been tested EF CTP5 Poco.

    Good luck