[英]How to force a query to retrieve nested elements data?
I'm making a JSON
from my Database made with LINQ to SQL
. 我正在使用
LINQ to SQL
从数据库中创建JSON
。 I've set up Serialization Mode Unidirectional
(so I can serialize data), and once I query my Object ( User
) I convert it to JSON
: 我已经设置了
Serialization Mode Unidirectional
(因此我可以串行化数据),并且一旦查询了对象( User
),便将其转换为JSON
:
[WebMethod]
public User GetUserByID(int ID)
{
User user = db.User.Where(p => p.ID == ID).FirstOrDefault();
var json = JsonConvert.SerializeObject(user, new IsoDateTimeConverter());
return user;
}
The problem is that on the resulting JSON
, the nested data/objects (ie the relationship I have for that Object to others Object/Tables) are null
. 问题在于,在生成的
JSON
,嵌套的数据/对象(即我对该对象与其他对象/表之间的关系)为null
。
So, for example, if I have 3 Phone numbers (1-n relationship) for that user, instead of retrieve a JSON
array with these (3) numbers, it puts: 因此,例如,如果我有该用户的3个电话号码(1-n关系),而不是检索具有这(3)个号码的
JSON
数组,则输入:
"Phones": null,
how can I "force" the User
to be queried with all data/relationship inside it? 如何“强制”向
User
查询其中的所有数据/关系?
And if I do this query (for example) before serialize: 如果我在序列化之前执行此查询(例如):
var phones = m_oAlumno.Telefono.ToList();
it says "Self referencing loop detected for type 'User'." 它说:“检测到类型为“用户”的自引用循环。”
In LINQ to SQL you can load referenced entities using DataLoadOptions. 在LINQ to SQL中,您可以使用DataLoadOptions加载引用的实体。
var loadOptions = new DataLoadOptions();
loadOptions.LoadWith<User>(u => u.PhoneNumber);
db.LoadOptions = loadOptions;
Where PhoneNumber is an entity that references User and assuming db is your linq data context. 其中PhoneNumber是引用User的实体,并假定db是您的linq数据上下文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.