Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a mass update in nhibernate?

Tags:

nhibernate

I am wondering how do a mass update? I want to do a where clause and grab all items that meet that where clause Where(x => x.Id == 1).ToList() then do an update on all of them.

// change every name to bob
A.Name = "bob"
// then do a mass update

Do I have to do a foreach loop? And go through each one and then send it to be updated or is there another way to do this?

Thanks

Edit

I have this

// in my repo;
  private readonly ISession session;

 // session done with ninject IOC
public MyRepo(ISession session)
{
   this.session = session;
}

public void MassUpdate(int id, string prefix)
{
         var query = "UPDATE TableA SET Name= (:prefix) WHERE Id IN (:Id)";
          session.CreateQuery(query).SetParameter("prefix", prefix).SetParameter("Id",Id);
}

 public void Insert(MyClass myClass)
 {
    sesson.save(myClass);
 }

public void Commit()
{
    using (ITransaction transaction = session.BeginTransaction())
     {
                    transaction.Commit();
     }
}

 // service layer method

 public void myMethod()
 {
     MyClass myClass = nw MyClass() { Name = "test"};
     MyRepo r = new Repo();
     r.MassUpdate(1,"bob");
     r.Insert(myClass);
     r.Commit();
 }

So how can I setup my MassUpdate to execute on Commit(). Note that this commit is used for all methods in MyRepo so I can't stick the execute in the commit method.

like image 770
chobo2 Avatar asked Apr 17 '11 22:04

chobo2


2 Answers

Expanding Diego's answer's, you can use HQL to send a list of arguments:

var person = 25;
var query = "update Foo set Name = 'bob' where id = :person";
var update = session.CreateQuery(query)
                    .SetParameter("person", person);


/***
 *
 * Do Stuff
 *
 ***/

 update.ExecuteUpdate();
like image 192
rebelliard Avatar answered Oct 15 '22 15:10

rebelliard


session.CreateQuery("update Foo set Name = 'bob' where id = 1")
       .ExecuteUpdate()
like image 26
Diego Mijelshon Avatar answered Oct 15 '22 15:10

Diego Mijelshon