I am doing a project with WCF. And I have to deal with two dictionaries: one is a list of users, the other a list of groups.
That said, I manage to create, remove and search both users and groups by creating the appropriate messages. But I’m still clueless about adding users to groups.
So having a reference in users to be part of a group and groups to have a numbers of users.
Please let me know if you require more details.
User Dictionary:
private Dictionary<string, User> Users = new Dictionary<string, User>();
User Data Contract:
[DataMember(Name = "ID")]
public string ID;
/**
* First name of the User
*/
[DataMember(Name = "firstname")]
public string FirstName;
/**
* Last name of the User
*/
[DataMember(Name = "lastname")]
public string LastName;
/**
* The group that the User on
*/
[DataMember(Name = "group")]
public string Group;
Group Dictionary
private Dictionary<string, Group> groups = new Dictionary<string, Group>();
Group Data Contract
[DataMember(Name = "number")]
public string Number;
/**
* The name of the group
*/
[DataMember(Name = "group name")]
public string GName;
Thank you.
By adding a reference from the user to the group and the group to the user you are creating a circular reference, which is a code smell. The best way to go is have only one part reference the other.
The same as you’d do with Relation Databases, you’d write the order of the relationship between
UserandGroup. In this case, it’s 1:N (one-to-many): many users belong to a group, or a group has many users. So, as with databases, the “many part” gets a reference to the “one” part:While the group wouldn’t know anything about its users:
However, this also means you have a inverted navigation — you can’t navigate from groups to users directly. If that’s a necessity, you can invert the relationship between users and groups, by having the Group class hold a list of users and users know nothing about groups.
The final point is that, for WCF to correctly serialize this structure, you have to stick it to a single instance of data contract, otherwise WCF won’t know that the Group referenced in the User are actually part of your list of groups, so:
Finally, your Group and User data contracts are using public fields. This isn’t good practice in .Net: convert then to properties or auto-properties.