mrblah
mrblah

Reputation: 103517

Creating an Update method in my nHibernate repository

My current repository looks like:

 public class Repository<T> : IRepository<T>
    {

        public ISession Session
        {
            get 
            { 
                return SessionProvider.GetSession(); 
            }
        }


        public T GetById(int id)
        {
            return Session.Get<T>(id);
        }

        public ICollection<T> FindAll()
        {
            return Session.CreateCriteria(typeof(T)).List<T>();
        }

        public void Add(T t)
        {
            Session.Save(t);
        }

        public void Remove(T t)
        {
            Session.Delete(t);
        }


    }

the interface:

 public interface IRepository<T>
    {
        T GetById(int id);
        ICollection<T> FindAll();
        void Add(T entity);
        void Remove(T entity);
    }

How would I create an update method?

Do I have to call flush or transaciton commit to write to the database?

I have tried updating an object, and calling saveorupdate(); but it didn't change the value in the db.

Upvotes: 0

Views: 1042

Answers (2)

Paco
Paco

Reputation: 8381

You don't. The repository pattern means: "emulate a normal collection for persistence usage" With normal collection, I mean something like List<T> When you do this:

var list = new List<User>();
list.Add(myUser);
myUser.MyProperty = newValue;

MyProperty for the user in both the list and the myUser variable are set to newValue, because it's the same reference. It would be rather strange to do this instead:

var list = new List<User>();
list.Add(myUser);
myUser.MyProperty = newValue;
list.Update(myUser);

Repository should behave the same as other collections, like list. When you need an explicit update, please do not call it a repository. Collections do not work like that.

To answer your question: Yes you have to commit a transaction or flush the session to change persist the changes in the session in the database. It might be better to make a unit of work responsible for this, instead of the repository, and inject the unit of work into the repository, instead of the session.

Upvotes: 3

Shane Courtrille
Shane Courtrille

Reputation: 14097

We don't actually have an Add method on our repositories. Instead we just have a Save method (not in love with the name). The method does a Session.SaveOrUpdate() which works fine since we have unsaved-value specified on our definitions.

In terms of seeing actual changes to the database this doesn't occur until you close your session. This saves NHibernate from doing any work until it absolutely has to.

The only reason you would ever need to flush is if you wanted to get an id back from your database but it's for this reason that identity isn't preferred NHibernate Avoid Identity Generator When Possible

Upvotes: 1

Related Questions