简体   繁体   English

LINQ to Entities返回实体的孩子的孩子的错误ID

[英]LINQ to Entities returns wrong ID for an entity's child's child

I have a table structure in MySql, set up with foreign keys: 我在MySql中有一个表结构,用外键设置:

Period { Id, Title } 期间{ID,标题}

Activity { Id, Title, PeriodId } 活动{ID,标题,PeriodId}

Resource { Id, FileName } 资源{ID,文件名}

ActivityResources { ActivityId, ResourceId } ActivityResources {ActivityId,ResourceId}

This is set up with LINQ-to-Entities and I have checked that the table mappings are correct incuding the many-to-many relationship. 这是使用LINQ-to-Entities设置的,并且我检查了表映射是否正确(包括多对多关系)。 Normally all works well with the Period , Activity and Resource classes. 通常,所有这些都可以与PeriodActivityResource类一起很好地工作。

However, I am trying to use this code: 但是,我正在尝试使用以下代码:

private string ListAttachments(Ctx ctx) {
  var resList = new StringBuilder();
  var p = ctx.Periods.Include("Activities.Resources").Single(o => o.Id == 1);
  foreach (var a in p.Activities) foreach (var r in a.Resources)
    resList.Append(r.Id).Append(" - ").Append(r.FileName);
  return resList.ToString();
}

But it doesn't write the Resource.Id for each resource as expected; 但是它没有按预期为每个资源编写Resource.Id for some reason it writes the Activity.Id instead (though the FileName is correct). 由于某种原因,它改写了Activity.Id (尽管FileName是正确的)。

Any idea what's going on? 知道发生了什么吗?

EDIT 编辑

By the way, this works fine - but I'm still interested in the probem in the above code. 顺便说一句,这可以正常工作-但我仍然对上述代码中的probem感兴趣。

private string ListAttachments(Ctx ctx) {
  var resList = new StringBuilder();
  var res = ctx.Resources.Where(r => r.LessonActivities.Any(l => l.LessonId == 1)).ToList();
  foreach (var r in res) resList.Append(r.Id).Append(" - ").Append(r.FileName);
  return resList.ToString();
}

I don't think you can reference a child/child collections that way. 我认为您无法以这种方式引用儿童/儿童收藏。 The Activities navigation property on a Period object is a collection. Period对象上的“ Activities导航属性是一个集合。 And you can't reference a property that belongs to an instance of an object via a collection of those objects. 而且,您无法通过这些对象的集合来引用属于该对象实例的属性。

Put another way, Period p has an Activities collection. 换句话说, Period p具有Activities集合。 But a collection of type Activity does not have a Resources collection. 但是Activity类型的集合没有 Resources集合。 Only a single Activity has a Resources collection. 只有一个Activity具有Resources集合。

What I don't understand is why the first snippet works at all. 我不明白的是为什么第一个代码片段根本无法工作。

Anyway, to get to the Resources collection directly from a Period , you would need to use SelectMany() . 无论如何,要直接从Period进入Resources集合,您将需要使用SelectMany() Something like 就像是

List<Resource> resources = ctx.Periods
                              .Where(p=>p.Id == 1)
                              .SelectMany(p=>p.Activities)
                              .SelectMany(a => a.Resources)
                              .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM