【发布时间】:2014-02-12 06:37:19
【问题描述】:
我正在使用 EF 和 MVC 访问 SQL 数据库中的数据,并希望控制器使用 json 进行通信(使用 Android 中的 REST,因此不使用视图)。
我发现有必要更改控制器以通过匿名对象投影数据以避免主表和引用表之间的循环引用问题,但是当尝试为集合创建 json 时,这导致了一个新问题对象,当基础记录在可选外键字段中包含 null 时。
表用户(例如)有两个外键来编码/描述表语言和国家,语言是强制性的,国家是可选的。
我发现我可以通过测试 null id 成功地将 Country 元素替换为 null。json 出来很好......
{
"UserID": 3,
"UpdatedWhen": null,
"Country": null,
"Language": {
"LanguageID": 1,
"LocalName": "English"
}
}
...但现在发现当我有多个 User 对象要处理时,这不起作用。
public JsonResult Index()
{
var users = from user in db.Users
select new
{ user.UserID,
< snip >
user.CreatedWhen,
user.UpdatedBy,
user.UpdatedWhen,
Country = (user.Country == null ? null : new { user.Country.CountryID, user.Country.LocalName }),
Language = new { user.Language.LanguageID, user.Language.LocalName } };
return Json(users.ToList(), JsonRequestBehavior.AllowGet);
}
从我读到的问题在于我的 .ToList(),它不喜欢 null Country 对象,因为如果我只处理单个用户,例如
private object projectUser(User user)
{
return new
{
user.UserID,
< snip >
user.UpdatedWhen,
Country = (user.Country == null ? null : new { user.Country.CountryID, user.Country.LocalName }),
Language = new { user.Language.LanguageID, user.Language.LocalName } };
...它工作得很好。
我一直在寻找,但根本找不到一个足够相似的例子来说明如何更好地做到这一点,谁能建议一个方法。
提前致谢。
【问题讨论】:
标签: c# json linq entity-framework asp.net-mvc-4