开发者

Nhibernate (and ORMs in General): work with Objects or ObjectIds?

开发者 https://www.devze.com 2023-01-09 03:36 出处:网络
This is something that has been pulling at me for a while.Consider a (MVC type) web application with an ORM (e.g. Nhiberate) as the data access layer.

This is something that has been pulling at me for a while. Consider a (MVC type) web application with an ORM (e.g. Nhiberate) as the data access layer.

On one hand - the OOP/Rich domain model hand - I feel I should be passing around (references to) the real objects I am talking about.

On the other hand开发者_如何转开发 - the DB/Web App hand - I feel that it is easier and more efficient just to pass the integer Ids of the objects rather than the object themselves.

Consider an ecommerce catalogue type application:

  • The user is logged in and navigates to a product page.
  • They post a comment.
  • The controller action tasked with persisting this comment has 3 pieces of information: a) The user id (from the auth cookie or wherever), b) The product id (probably from the querystring), and c) the comment text.
  • Now, what what is best practice here? Is it really worth inflating the user and product objects (e.g. by getting them from the repository, with all the DB work that entails) when we know that all they will be used for is so the ORM can read their IDs and set the appropriate foreign keys in the DB table that stores the comments?

What are peoples views on this? Perhaps web apps should be given a little more leway than other apps, due to their stateless nature? I imagine there will be 'it depends' answers, but maybe some people are purists about the issue.

This is a general question which probably is applicable to many platforms, but if giving examples I would prefer them to be ASP.NET MVC if possible.

Thank you.


NHibernate has the load operation (as opposed to doing a get) exactly for this reason.

session.Save(
  new Comment
      {
         Text = commentTextFromScreen,
         User = session.Load<User>(userID),
         Product = session.Load<Product>(productID)
      }
};

In the above example, you are telling NHibernate: I know these already exist in the database, so don't bother selecting them right now. NHibernate will return proxy objects for them and a select won't happen against the database as long as you don't attempt to access any properties on the objects.

For more info check out Ayende's blog post: The difference between Get, Load, and query by id.

0

精彩评论

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