开发者

NHibernate / ORM - Child Update over Web Service

What is the correct way to UPDATE a child object with NHibernate but not have to "awake" the parent object. Lets say you would like to try to avoid this because the parent object is large or expensive to initiate.

Lets assume classes are called Author(parent) and Book(child). (still, trying to avoid instantiating Author)

Book comes back over a web service as XML. It gets deserialized back into a CLR object. Book has an AuthorId property which allows this to happen. But开发者_开发问答 it also has a Author property.

Problem, comes when you try to SaveOrUpdate() Book and the author_id in the database gets wiped out because the Author was null when the object gets deserialized. This seems like this would be a common problem. What is the workaround?

Also, if you instantiate the Author and it has a Books property. The book you are trying to update is already one of these books (List<Book>). We have also run into the "a different object with the same identifier value was already associated with the session" problems. What is the standard process to update a child over a web service?


First, your persistent Book entity should only have a Author reference, not an AuthorId. You should use a DTO for your service that contains AuthorId and not Author.

After that, the code is simple:

using (var tx = session.BeginTransaction())
{
  var book = session.Get<Book>(bookDTO.Id);
  MapAllSimplePropertiesFromDTO(bookDTO, book);
  book.Author = session.Load<Author>(bookDTO.AuthorId);
  tx.Commit();
}

session.Load<Author> creates a proxied reference to the Author by id without going to the database.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜