I am dealing with a problem i cannot solve by myself. I also tried to find out a solution on the net, without success.
Here the details ...
Its about a complex data binding (in this case , 3 database tables).
Here the tables i have (abstraction), trying to modelate a Users/Groups association
Table 1 - tblUsers
------------------------------
field1: Id
field2: Username
field3: Password
Table 2 - tblGroups
------------------------------
field1: Id
field2: GroupName
field3: Description
Table 3 - tblUsers_Groups
------------------------------
field1: Id
field2: Id_tblUsers
field3: Id_tblGroups
This way a single user can belong to multiples groups (and vice)
I have been trying to create a WinForm, like the Master - Detail kind, where the Master Grid should show the Users in tblUsers, and ... according to what I select there, show in the Details Grid, the groups the users selected belongs to ... but using the info in tblGroups
Could someone please give me a hand on this problem?
First table 3 should not have and ID
Use a composite key of Id_tblUsers, Id_tblGroups
In .NET the way I do it is
public class UserGroup : Object
{ // NO editing just add remove
public User User { get; private set; }
public Group Group { get; private set; }
public override bool Equals(Object obj)
{
//Check for null and compare run-time types.
if (obj == null || !(obj is UserGroup)) return false;
UserGroup item = (UserGroup)obj;
return (User.ID == item.User.ID && Group.ID == item.Group.ID);
}
public override int GetHashCode() { return (User.ID & 0xffff) + (Group.ID << 16); }
public UserGroup(User user, Group group)
{ User = user; Group = group; }
}
Create a HashSet of UsersGroups and pass it to both Group and User in the ctor.
It is just a reference to an object so everyone is referencing the same data.
Override GetHash for efficiency and Equals so cannot have a duplicate UserGroup in the HashSet.
The is the code for returning the groups a user is in
public List<Group> Groups
{ get { return usersGroups.Where(x => x.User == this)
.Select(x => x.Group)
.OrderBy(y => y.Name)
.ToList(); } }
Then the sister in Group to return users.
It may seem complex but what is cool is a single master. So when you revise HashSet of UserGroup it is reflected in both User and Group
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.