Sql LINQ不返回所有子记录

Sql LINQ不返回所有子记录,sql,entity-framework,linq-to-entities,Sql,Entity Framework,Linq To Entities,我在数据库中有一个查询: SELECT GreenInventoryBlendGradeID,bgx.blendgradeid, bgX.GreenBlendGradeTypeID,[Description] FROM [GreenInventory] gi INNER JOIN [GreenInventoryBlendGradeXref] bgX ON bgX.[GreenInventoryID] = gi.[GreenInventoryID] INNE

我在数据库中有一个查询:

SELECT  GreenInventoryBlendGradeID,bgx.blendgradeid,
        bgX.GreenBlendGradeTypeID,[Description]
  FROM [GreenInventory] gi 
 INNER JOIN [GreenInventoryBlendGradeXref] bgX 
    ON bgX.[GreenInventoryID] = gi.[GreenInventoryID] 
 INNER JOIN [BlendGrade] bg
    ON bg.[BlendGradeID]=bgx.[BlendGradeID]
返回3条记录:

类型描述


1 XR
2 XR
1 XF2

林克:

    var GreenInventory = (from g in Session.GreenInventory
                    .Include("GreenInventoryBlendGradeXref")
                    .Include("GreenInventoryBlendGradeXref.BlendGrade")
                    .Include("GreenInventoryBlendGradeXref.GreenBlendGradeType")
                    .Include("GreenInventoryWeightXref")
                    .Where(x => x.GreenInventoryID == id && x.GreenInventoryBlendGradeXref.Any(bg=>bg.GreenBlendGradeTypeID > 0) )
            select g);
我尝试了不同的Where子句,包括simple-(x=>x.GreenInventoryID==id) 但始终只返回前2条记录

有什么想法吗

如果我尝试以下方法:

var GreenInventory = (from gi in Session.GreenInventory.Where(y => y.GreenInventoryID == id)  
join bgX in Session.GreenInventoryBlendGradeXref.DefaultIfEmpty() on gi.GreenInventoryID equals bgX.GreenInventoryID  
join bg in Session.BlendGrade.DefaultIfEmpty()  on bgX.BlendGradeID equals g.BlendGradeID  
select new { GreenInventory = gi, GreenInventoryBlendGradeXref = bgX, BlendGrade = bg });
我得到每个对象中的3个,正确的信息在BlendGrade对象中。看起来这3个GreenInventory对象是相同的。它们每个都包括两个GreenInventoryBlendGradeXref对象,显示与以前相同的两条记录

所以我不清楚最初的问题是什么。也不知道这是否是解决问题的最佳方法


谢谢你的回答。如果有人有进一步的想法,请告诉我们

我首先要查看的是您的模型,以及您在实体之间定义的连接。您可能还需要检查生成的SQL语句:

Trace.WriteLine(GreenInventory.Provider.ToString())


或者使用Visual Studio IntelliTrace调查发送到数据库的内容。

我首先要查看的是您的模型以及您在实体之间定义的连接。您可能还需要检查生成的SQL语句:

Trace.WriteLine(GreenInventory.Provider.ToString())


或者使用Visual Studio IntelliTrace调查发送到数据库的内容。

根据您提供的一些详细信息,我认为您缺少一个连接。我没有使用EntityFramework的经验(我假设您使用此ORM),但据我所知,“.Include”尝试确保根实体集不会更改,也不会包含重复项

手动创建的查询似乎表明模型中至少存在一个1:n关系。从LINQ得到的结果表明,只返回不同的GreenInventory实体


因此,您需要调整查询并明确声明您需要所有结果(而不仅仅是不同的根实体)——我假设使用显式连接EntityFramework将产生所有预期结果——或者您需要调整映射。

根据您提供的一些详细信息,我假设您缺少连接。我没有使用EntityFramework的经验(我假设您使用此ORM),但据我所知,“.Include”尝试确保根实体集不会更改,也不会包含重复项

手动创建的查询似乎表明模型中至少存在一个1:n关系。从LINQ得到的结果表明,只返回不同的GreenInventory实体


因此,您需要调整查询并明确声明您需要所有结果(而不仅仅是不同的根实体)-我假设使用显式连接EntityFramework将产生所有预期结果-或者您需要调整映射。

我从现有数据库创建模型。是,数据库中的“我的模型”未正确更新以包含GreenInventoryBlendGradeXref表的新主键。如果可以,我会将此标记为答案:)我从现有数据库创建了模型。是的,数据库中的模型没有正确更新以包含GreenInventoryBlendGradeXref表的新主键。如果可以,我会将此标记为答案:)