开发者

How to do a mass update in nhibernate?

开发者 https://www.devze.com 2023-02-26 01:54 出处:网络
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.

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)开发者_如何学Go
{
         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.


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();


session.CreateQuery("update Foo set Name = 'bob' where id = 1")
       .ExecuteUpdate()


Sorry this is a late answer but just so you know a better solution (without query in plain text) exists here : Linq to Nhibernate Bulk Update Query Equivalent?

In your case it would be applied like this:

session.Query<TableA>().Where(f => f.Id == id)
            .Update(i => new Foo { prefix = myPrefix });
0

精彩评论

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