开发者

How to design the objects' relationship with ORM

I have been confused about ORM since I see the following sample code:

public class Article
{
    public List<Comment> Comments;

    public void AddCom开发者_Go百科ment(Comment comment)
    {
        Comments.Add(comment);
    }

    // I'm surprised by this kind of operation
    // how much performance hit it should be
    public void Save()
    { 
        //update the article and all its comments
    }
}

According to what I think, the responsiblity of saving comment should be assigned to the comment itself:

public class Comment
{
    public Article BelongArticle;

    //I think this is better/direct than use object Article,
    //But it's based on the consideration of database structure,
    //I was told one should "forget" the database, but it's really hard
    public int ArticleId;   

    public void Save()
    { 
        //save the comment directly
    }
}


You are reaching conclusions without any real basis because you are just looking at some sample code and not considering what actually might be happening.

The whole point of using an ORM is so you can allow it to handle the database transactions while you work in an object oriented rather than a relational fashion in your application. You really cannot say anything about how the ORM performs when you do an update on Article by just looking at Article.Save. Article.Save is an OO construct, and what the ORM actually executes on the database is a relational action. What about Article.Save makes you think it is inefficient? Looking at that does not give you any information. You would have to look at what the ORM of choice is doing on the database.

Suppose the Article is a new object. In this case you have to save the Article, set the foreign key in the Comment, and then save the comment. Your "preferred" code does not show the full operation but it still must occur. The difference is the ORM gives you an object oriented way to do this - just call save on the article. Under the hood the same operations must occur either way. Maybe the ORM takes more steps than you could do it in manually, but maybe not.

Suppose Article is not a new object. You add a new Comment. Depending on the platform, when you call Save this time potentially what happens with an ORM could be no different than what you might think as better depending on how your code is written. If there is nothing that needs to be updated in the Article, the ORM may simply save the Comment.

ORMs use various methods, but in general they maintain some kind of running account of objects that need to be updated.

You cannot just say that the first approach is somehow inefficient just on face because you called a method on Article instead of Comment - what is actually happening will depend on the specific ORM platform you use as well as the state of the objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜