实体框架 - 许多问题

时间:2009-11-13 11:08:42

标签: entity-framework .net-3.5 entity

我有一个名为ASB的表和一个名为PeopleInvolved的表。有一个名为PeopleInvolved_ASB的联结表,它只包含一个ASBID和一个PeopleInvolvedID列。这些列充当复合主键。

设计人员不显示联结表(如预期的那样)。我想根据ASBID检索PeopleInvolved列表。

要检索人员,我这样做:

 // This top line gets the ASB record from the Case
 var asbRecord = (from c in dd.Case
                         where c.CaseID == caseID
                         select c.ASB).First();

        var asbID = asbRecord.Select(asb => asb.ASBID).First();

        var people = (from asb in dd.ASB
                      where asb.ASBID == asbID
                      select asb.PeopleInvolved);

现在,我想要做的是将每个PeopleInvolved记录添加到PeopleInvolved类型的简单列表中。我不能这样做。我一直在说:

错误4无法将类型'System.Data.Objects.DataClasses.EntityCollection'转换为'Dynamic.PeopleInvolved'

如何将一个简单的PeopleInvolved列表导入到可以传递回控制器的通用列表中?

谢谢,

3 个答案:

答案 0 :(得分:1)

这是你想要做的?

 List<PeopleInvolved> genericPeopleInvolvedList = (from asb in dd.ASB
                          where asb.ASBID == asbID
                          select asb.PeopleInvolved).ToList();

[更新:之前回答错误]

刚才意识到asb.PeopleInvolved是集合而非单一实体(该死的!)。因此,之前的linq查询返回PeopleInvolved实体的CollectionS。由于您是通过ASPID选择的,因此只应该有一个asb.ASBID来填充where子句asb.ASBID == asbID,您可以执行以下操作:

var listWithCollectionOfPeopleInvolved = (from asb in dd.ASB
                              where asb.ASBID == asbID
                              select asb.PeopleInvolved).ToList();

List<PeopleInvolved> peopleInvolved = listWithCollectionOfPeopleInvolved.First().ToList();

但如果你使用Include:

这样做会更好
var asbInstance = (from asb in dd.ASB.Include("PeopleInvolved")
                      where asb.ASBID == asbID
                      select asb).FirstOrDefault();
foreach(PeopleInvolved pi in asbInstance.PeopleInvolved)
{
//do your stuff
}

使用Include自动加载相关属性。

答案 1 :(得分:1)

根据您报告的错误,我猜猜PeopleInvolved是一个集合。所以试试这个:

    var people = (from asb in dd.ASB
                  where asb.ASBID == asbID
                  from pi in asb.PeopleInvolved
                  select pi).ToList();

我认为非常令人困惑的是同时拥有一个名为PeopleInvolved的类型和具有完全相同名称的该类型的集合。同样,您似乎有一个名为ASB的类型和一个实体集,其中包含许多具有相同名称的该类型的实例,

使实体集名称复数和类型名称为单数更清晰。

如果我猜错了类型,请澄清ASBDynamic.PeopleInvolveed的布局。

答案 2 :(得分:0)

List<PeopleInvolved> = new List<PeopleInvolved>(people);