NHibernate - Linq 检索的实体可以更新吗?
如果我有一个使用 NHibernate 持久保存的实体 Foo
,并使用 Linq 检索它,如下所示:
var foos = FooRepository.GetFoos.Where(x => x.LikesWearningFunnyHats == true);
然后像这样弄脏每个 Foo
:
foo.LikesWearingFunnyHats = false;
并告诉存储库保存it:
FooRepository.Save(foo);
我目前发现 Foo
没有被保存。这是因为我使用 Linq 而不是通过 ID 或通过关联来检索它们吗?
If I have an entity Foo
which I'm persisting using NHibernate and I retrieve it using Linq like so:
var foos = FooRepository.GetFoos.Where(x => x.LikesWearningFunnyHats == true);
I then dirty each Foo
like so:
foo.LikesWearingFunnyHats = false;
And tell the repository to save it:
FooRepository.Save(foo);
I'm currently finding that the Foo
s are NOT being saved. Is this because I'm retrieving them using Linq rather than by ID or through an association?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不应该是因为您使用的是 Linq。 Linq 表达式树只是转换为与 IQuery 或 HQL 字符串相同的 ANTLR 原语,然后从那里转换为 SQL。
确保在完成持久性操作后刷新会话和/或提交该会话中固有的事务。您应该了解 NHibernate 在您和数据库之间提供了一层隔离,旨在决定何时向数据库发送更新,以节省与数据库服务器的往返次数。通常,它是“批量”进行的;它会收集十到二十条语句,然后将它们作为一批推送到 SQL Server。如果您一次性执行的工作单元较小,则必须使用 ForceFlush() 方法强制会话执行 SQL 更新,从而覆盖其推迟发送更新的决定。
最好通过公开会话或其包含的存储库的方法来在会话内创建、提交和回滚事务,从而使其在外部可控。
It shouldn't be because you're using Linq. The Linq expression tree is just translated into the same ANTLR primitives that an IQuery or HQL string would be, and from there to SQL.
Make sure you're flushing the Session, and/or committing the Transaction inherent in that Session, after completing a persistence operation. You should understand that NHibernate provides a layer of separation between you and the database, and is designed to decide when to send updates to the DB, to economize on round trips to the DB server. Usually, it does so in "batches"; it'll collect ten or twenty statements before pushing them as one batch to SQL Server. If you're doing smaller units of work than that at one time, you must override its decision to hold off on sending the update by forcing the session to perform a SQL update, using the ForceFlush() method.
It would be best to make this externally controllable, by exposing methods of the Session or its containing Repository to create, commit and rollback transactions within the Session.
你认为为什么实际上没有得救?尝试调用 session.Flush() 并确保提交事务以查看 NH 是否会发出正确的命令。获取实体的事件策略应该不重要。
Why do you think is not actually saved ? Try to call session.Flush() and ensure committing the transaction to see if NH will issue the proper command. Event strategy for fetching the entity should not matter.