relationships in rest?

2019-04-09 23:15发布

问题:

I want to add a person to a community and im not sure how its done?

My datacontract looks like this:

[DataContract(Name = "Community")]
public class Community
{

    public Group() 
    {
        People = new List<Person>();
    }
    [DataMember(Name = "CommunityName")]
    public string CommunityName { get; set; }
    public List<Person> People { get; set; }

}
[DataContract(Name = "Person")]
public class Person
{
    [DataMember(Name = "PersonName")]
    public string PersonName { get; set; }
}

In my service I can add a person or a community like so:

List<Community> Communitys = new List<Community>();
List<Person> people = new List<Person>();
public void AddCommunity(Community community)
{
     Communitys.Add(community);
}
public void AddPerson(Person person)
{
     people.Add(person); 
}

public void AddPersonToCommunity(Person person, Community community)
{
    //not sure what to do here
} 

But I am unsure how to join a person to a community

public void AddPersonToCommunity(Person person, Community community)
{
    //community.CommunityName(Person.Add);?
} 

And I have a windows form which when I POST either a person or a community it is done like so:

{
    StringBuilder Community = new StringBuilder();
    Community.AppendLine("<Community>");
    Community.AppendLine("<CommunityName>" + this.textBox4.Text + "</CommunityName>");
    Community.AppendLine("</Community>");

But How would you (once completed) take the AddPersonToCommunity and make a string builder in order to add a person to a community?

    {
        StringBuilder CommunityAddPerson = new StringBuilder();
        CommunityAddPerson.AppendLine("<Community&{1}>");
        CommunityAddPerson.AppendLine ......
        CommunityAddPerson.AppendLine("<CommunityName>" + this.textBox4.Text + "</CommunityName>");
        CommunityAddPerson.AppendLine("</Community>");

Hope this is more clear its two questions in one I guess.

回答1:

I think your method, based on what you are saying, might look like this:

public void AddPersonToCommunity(string person, string communityName)
{
    var result = communities.Where(n => String.Equals(n.CommunityName, communityName)).FirstOrDefault();
    if (result != null)
    {
        result.Add(new Person() { Name = person });
    }
} 

Your POST data may look like this:

<Community>
  <CommunityName>CrazyTown</CommunityName>
  <People>
     <Person>Moe Howard</Person>
  </People>
</Community>


回答2:

You could always add a method to add a person to a community:

public void AddPersonToCommunity(Person person, Community community)...

or

public void AddPersonToCommunity(string personName, string communityName)...