特拉维斯,我知道你在这里有你接受的答案,但想就此进行一点横向思考。我最近遇到了一个非常相似的问题,无法为我工作,尝试了所有的 [scriptignore] 属性等,等等。
最终对我有用的是使用 Automapper 并创建从代理对象到精简的 poco 对象的映射。这在 2 分钟内解决了我所有的问题。在试图让代理打球时,经过 36 小时的围攻心态占了上风 - 嘘 :-)
在此期间要考虑的另一种方法。
[编辑] - 使用 Automapper(这是一个引用 automapper 的小测试应用程序)
参考:http ://automapper.codeplex.com/
nuget:安装包 AutoMapper
课程:
public sealed class One : BaseViewModel
{
// init collection in ctor as not using EF in test
// no requirement in real app
public One()
{
Two = new Collection<Two>();
}
public int OneId { get; set; }
public ICollection<Two> Two { get; set; }
}
public class Two
{
public int TwoId { get; set; }
public int OneId { get; set; }
[ScriptIgnore]
public virtual One One { get; set; }
}
public abstract class BaseViewModel
{
public string AsJson()
{
var serializer = new JavaScriptSerializer();
return serializer.Serialize(this);
}
}
public class OnePoco : BaseViewModel
{
public int OneId { get; set; }
public virtual ICollection<TwoPoco> Two { get; set; }
}
public class TwoPoco
{
public int TwoId { get; set; }
public int OneId { get; set; }
}
测试控制器代码:
public ActionResult Index()
{
// pretend this is your base proxy object
One oneProxy = new One { OneId = 1 };
// add a few collection items
oneProxy.Two.Add(new Two() { OneId = 1, TwoId = 1, One = oneProxy});
oneProxy.Two.Add(new Two() { OneId = 1, TwoId = 2, One = oneProxy});
// create a mapping (this should go in either global.asax
// or in an app_start class)
AutoMapper.Mapper.CreateMap<One, OnePoco>();
AutoMapper.Mapper.CreateMap<Two, TwoPoco>();
// do the mapping- bingo, check out the asjson now
// i.e. oneMapped.AsJson
var oneMapped = AutoMapper.Mapper.Map<One, OnePoco>(oneProxy);
return View(oneMapped);
}
试一试,看看你的进展如何,它确实对我有用,“地球”动了:)