Fluent NHibernate - “无法延迟初始化集合” - 查询集合
我有一个自引用模型类:
public class Word
{
public virtual int Id { get; set; }
public virtual string Text { get; set; }
public virtual IList<Word> Synonyms { get; set; }
public virtual int Extra { get; set; }
}
我正在尝试查询 Extra 为 1 的单词的所有同义词,并在我的 MVC 3 应用程序中返回 JSON 格式的单词列表:
[HttpPost]
public JsonResult Synonyms(string wordText)
{
using (var session = ...)
{
using (var tx = session.BeginTransaction())
{
var word = session.QueryOver<Word>()
.Where(w => w.Text == wordText)
.SingleOrDefault();
var results = new SynonymsResults()
{
Words = word.Synonyms
.Where(x => x.Extra == 1)
.Select(x => x.Text)
};
return Json(results);
}
}
}
我收到一条错误,指出它无法延迟执行初始化集合。我不知道为什么,因为我仍然在同一个会话中,甚至使用事务。
I have a self-referential model class:
public class Word
{
public virtual int Id { get; set; }
public virtual string Text { get; set; }
public virtual IList<Word> Synonyms { get; set; }
public virtual int Extra { get; set; }
}
I am trying to query for all synonyms of a word where Extra is 1 and returning the list of words in JSON format in my MVC 3 app:
[HttpPost]
public JsonResult Synonyms(string wordText)
{
using (var session = ...)
{
using (var tx = session.BeginTransaction())
{
var word = session.QueryOver<Word>()
.Where(w => w.Text == wordText)
.SingleOrDefault();
var results = new SynonymsResults()
{
Words = word.Synonyms
.Where(x => x.Extra == 1)
.Select(x => x.Text)
};
return Json(results);
}
}
}
I'm getting an error that it fails to lazily initialize the collection. I'm not sure why though, since I am still in the same session here and even using a transaction.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
结果执行的时间要晚得多,即在操作完成运行之后并且在会话之外。您返回
Json(results)
并不意味着这些结果将立即序列化为 JSON。该操作将首先完成执行,然后 ASP.NET MVC 管道将处理结果的执行 (OnResultExecuting),此时 JavaScriptSerializer 将接触集合。那时会话和交易早已不复存在。因此,要么指示您的 ORM 急切地获取依赖集合,要么更好地查看 以下一系列博客文章并使用视图模型。
The result executes much later, after the action has finished running and outside of the session. The fact that you have returned
Json(results)
doesn't mean that these results will be immediately serialized into JSON. The action will first finish executing, then the ASP.NET MVC pipeline will handle the execution to the result (OnResultExecuting) and it is at this point that the JavaScriptSerializer will touch the collection. At that point of time sessions and transactions are long gone.So either instruct your ORM to eagerly fetch the dependent collections or even better take a look at the following series of blog posts and use view models.
要消除错误,请安装 Nuget Pacakage Manager Newton.JSON 并映射到适当的项目并使用 [JsonIgnore] 修饰属性,这将跳过序列化问题,并且您不会收到错误。
To get rid of the error, install Nuget Pacakage Manager Newton.JSON and map to the appropriate project and decorate the property with [JsonIgnore], this will skip the serialization issues and you won't get the error.