[Error]: No persister for: System.Collections.Generic.List (when saving a collection only)
I'm getting an exception when saving a List in nHibernate, but saving an individual entity works fine.
Here's some sample code:
var dataSources = session.CreateQuery("from DataSource").List<DataSource>();
session.Save(dataSources[0]); //<--- This line works
session.Save(dataSources); //<--- This line does not
The error I am getting is:
No persister for: System.Collections.Generic.List`1[[MyCo.MyApp.Domain.EntityClasses.DataSource, MyCo.MyApp.Domain.Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
So as you can see, it can persist an individual entity, but a collection of those entities fails.
Note: fwiw, my *.hbm.xml are built as embedded resources.
Solution
ISession.Save() can only save individual entities, not collections, that's just the way it is. But all the writes will happen when Flush() is called. Interestingly, it seems a person doesn't even have to call Save() at all:
var dataSources = session.CreateQuery("from DataSource").List<DataSource>();
DataSource zDataSource = dataSources[0];
zDataSource.Description = "hello world" + System.DateTime.Now.ToString();
DataSource zDataSource2 = session.Get<DataSource>(222);
zDataSource2.Description = "he开发者_如何转开发llo world" + System.DateTime.Now.ToString();
session.Flush();
In the above example, both modified DataSource objects will be persisted to the database. So why does Save() exist....hmmmm.
That's because you can't save a collection of entities like that. Fortunately since these entities are already persisted and loaded into the cache, you actually don't need to do anything as the Session will save them next time it is flushed.
精彩评论