JSON +延迟加载
伙计们,我遇到了一个问题...
我的 User 类有一个属性 UserType userType ,如下所示:
public class User
{
public virtual int Id { get; set; }
public virtual string User { get; set; }
public virtual string Name { get; set; }
public virtual UserType userType { get; set; }
}
我无法返回 JSON,像这样...
[HttpGet]
public JsonResult JSONUsers(string q)
{
IEnumerable<User> model = dataServ.Users.GetUsers( q );
return this.Json( new { Result = model }, JsonRequestBehavior.AllowGet );
}
我收到错误:
检测到循环引用 序列化类型的对象时 'System.Reflection.RuntimeModule'。
我收到此错误的原因是延迟加载(至少这是我所理解的),并且为了不好地解决它,我做了:
public JsonResult JSON(string q)
{
List<User> model = new List<User>();
IEnumerable<User> users= dataServ.Users.Getusers( q );
foreach (var item in users)
{
User user = new User
{
Id = item.Id,
Name = item.Name
};
model.Add( user );
};
return this.Json( new { Result = model }, JsonRequestBehavior.AllowGet );
}
我不认为这是一个好的解决方案。在本例中,我只需要“Id”和“Name”属性,但如果我需要所有属性怎么办?需要一张一张的复制吗? 谁能告诉我是否有更好的解决方案?
谢谢,
蒂亚戈
Guys, I'm havin a problem with this...
My User class has a property UserType userType like below:
public class User
{
public virtual int Id { get; set; }
public virtual string User { get; set; }
public virtual string Name { get; set; }
public virtual UserType userType { get; set; }
}
I can't return a JSON, like this...
[HttpGet]
public JsonResult JSONUsers(string q)
{
IEnumerable<User> model = dataServ.Users.GetUsers( q );
return this.Json( new { Result = model }, JsonRequestBehavior.AllowGet );
}
I'm getting an error:
A circular reference was detected
while serializing an object of type
'System.Reflection.RuntimeModule'.
The reason I'm getting this error is the Lazy-Load (at least that's what I understood), and to poorly solve it, I did:
public JsonResult JSON(string q)
{
List<User> model = new List<User>();
IEnumerable<User> users= dataServ.Users.Getusers( q );
foreach (var item in users)
{
User user = new User
{
Id = item.Id,
Name = item.Name
};
model.Add( user );
};
return this.Json( new { Result = model }, JsonRequestBehavior.AllowGet );
}
I don't think this is a good solution. In this case I only need de "Id" and "Name" properties, but what if I need all properties? Will I have to copy one by one?
Can Anybody tell me if there is a better solution?
Thanks,
Thiago
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Ayende 写了一个很棒的系列有关此问题的博客文章。
但总结一下:使用视图模型 =>顺便说一句,这就是我在 StackOverflow 上回答的有关 ASP.NET MVC 的一半以上问题的解决方案。
Ayende wrote a great series of blog posts about this problem.
But to summarize: USE VIEW MODELS => and by the way that's the solution to more than half of the questions on StackOverflow about ASP.NET MVC that I am answering.