views:

57

answers:

1

We are modifying our post on stackoverflow.

And we only changed the tags part,removed tag1,tag2 and added tag3,tag4.

After pressing the Post Your Question button,these things should be done:

  1. reduced the count column for tag1,tag2 by 1
  2. delete the relation between the post and tag1,tag2
  3. if tag3,tag4 already exists,increase the count column of the two by 1;otherwise,insert them to the tags table with count value 1
  4. add the relation between the post and tag3,tag4

Let's take a deep breath and that's all!

I want to see which ORM can approach this most easily/performant no matter it's written in PHP/Java/C/.Net or any language else,because the ideas are similar across languages!

A: 

In DataObjects.Net it will look like this. There is now any mapping files because database schema is automatically generated by ORM, including auxiliary table for question-tag relation.

Tag class:

[HierachyRoot]
public class Tag : Entity
{
  [Field, Key]
  public int Id { get; private set; }

  [Field(Length = 100, Indexed = true)]
  public string Name { get; private set; }

  [Field]
  public int QuestionsCount { get; set; }

  public Tag(string name) 
  {
    Name = name;
  }
}

Question class:

[HierachyRoot]
public class Question : Entity
{
  [Field, Key]
  public int Id { get; private set; }

  [Field]
  public EntitySet<Tag> Tags { get; private set; }

  // Business methods (can be placed in separate service class)

  public void AddTag(string name)
  {
    var tag = Query.All<Tag>().SingleOrDefault(t => t.Name == name);
    if (tag==null)
      tag = new Tag(name) { QuestionsCount = 1 }
    else
      tag.QuestionsCount++;
    Tags.Add(tag);
  }

  public void RemoveTag(string name)
  {
    var tag = Query.All<Tag>.Single(t => t.Name == name);
    tag.QuestionsCount--;
    Tags.Remove(tag);
  }
}

Application code:

using (Session.Open())
using (var transactionScope = Transaction.Open())
{
  var question = Query.Single<Question>(questionId);

  question.RemoveTag("tag1");
  question.RemoveTag("tag2");

  question.AddTag("tag3");
  question.AddTag("tag4");

  transactionScope.Complete();
}
Alex Kofman
So it'll use lots more queries than pure(non-ORM) procedural programming?
See this post for what I mean by non-ORM solution,it only requires two queries for however many tags:http://stackoverflow.com/questions/2392827/how-to-deal-with-m2m-relationshipposts-and-tags-by-doctrinein-symfony