我在两个元素Sfera和Contenuti之间有一个N-N关系。
在Sfera项目上,我看到了Contenuti实体集,在Contenuti中我看到了Sfera集......
当我按代码添加新项目时,我使用如下结构:
using (IndexDB DB = new IndexDB())
{
try
{
var newContenuto = new Contenuto();
newContenuto.Cancellato = false;
newContenuto.PK_Content_ID = tt_content_id;
newContenuto.URL = URL;
foreach(long sphere in SphereID)
{
try
{
var sfere = from sfera in DB.Sfera where sfera.PK_Sfera == sphere select sfera;
newContenuto.Sfera.Add(sfere.First());
sfere.First().Contenuto.Add(newContenuto);
}
catch (Exception exc)
{
return new StandardResponse() {Success = false, Message = exc.Message};
}
}
DB.AddToContenuto(newContenuto);
DB.SaveChanges();
return new StandardResponse() {Success = true};
}
catch (Exception e)
{
return new StandardResponse() { Success = false, Message = e.Message + e.StackTrace };
}
如果我查看我的数据库,它会很好地存储我在右边的两个元素之间的关系" N-N" table ....但是当我尝试访问元素Contenuto.Sfera和Sfera.Contenuto总是空集......
要访问我做类似的事情:
using (IndexDB DB = new IndexDB())
{
var sfere = from sfera in DB.Sfera where sfera.PK_Sfera == IDSfera && sfera.Attiva select sfera;
if (!sfere.Any())
{
response.Add(new UrlResponse() { Success = false, ErrorMessage = "" });
}
var sferaSelezionata = sfere.First();
//HERE sferaSelezionata.Contenuto.Count == 0 even if on DB there are MANY "connections"
}
}
我该如何处理?
非常感谢!
答案 0 :(得分:1)
尝试在查询中使用Include()
。
var sfere = from sfera in DB.Sfera.Include("Contenuto") where sfera.PK_Sfera == IDSfera && sfera.Attiva select sfera;