views:

76

answers:

1

Hi,

I'm using POCOs in combination with EF4 and some entities are in many-to-many relationships, in my case objects of class User and objects of class PrivilegeGroup.

This is how class User looks like:

public class User
{
    public int UserID { set; get; }
    public string UserName { get; set; }
    public string UserPassword { get; set; }
    public bool IsActive { get; set; }

    public List<PrivilegeGroup> PrivilegeGroups { get; set; }
}

And this is how class PrivilegeGroup looks like:

public class PrivilegeGroup
{
    public int PrivilegeGroupID { get; set; }
    public string Name { get; set; }

    public List<User> Users { get; set; }
    public List<HasPrivilege> HasPrivileges { get; set; }
}

I have extended ObjectContext class as follows:

public class AdminMDSContext : ObjectContext
{

    public AdminMDSContext(string connectionString)
        : base(connectionString)

    {
        this.DefaultContainerName = "MDSUsers_Entities";
        _users = CreateObjectSet<User>();
        _privilegeGroups = CreateObjectSet<PrivilegeGroup>();

    }


    private ObjectSet<User> _users;
    private ObjectSet<PrivilegeGroup> _privilegeGroups;

    public ObjectSet<User> Users
    {
        get { return _users; }
    }


    public ObjectSet<PrivilegeGroup> PrivilegeGroups
    {
        get { return _privilegeGroups; }
        set { _privilegeGroups = value; }
    }

}

Querying and insertion of these entities are working fine, but deletion is making problem, i.e. I want to remove PrivilegeGroup from one User without db roundtrip, but I don't know how to do it.

Can anyone please help me?

Regards, DP

+1  A: 

Interesting question. Here is how u do it.

var user = new User { UserId = 1 };
var admin = new Privilege { PrivilegeId = 1 };
user.Privileges.Add(admin);
db.Users.Attach(user);
user.Privileges.Remove(admin);
db.SaveChanges();

There are total of 4 different approaches to solving the same problem. but i think from what u are telling me, this should suffice but if u need more info, you can ping me directly through mail

zeeshanhirani
Thank you very much, zeeshanhirani! There was one thing though, I had to add additional two lines:if (user.Privileges == null) user.Privileges = new List<Privilege>();
Deveti Putnik