Linq to Entities - 使用“自引用”检索实体来自存储过程

发布于 2024-08-02 14:57:27 字数 774 浏览 4 评论 0原文

我不太明白这一点。我有一个名为 Employee 的表,其中包含 Id 字段。该表还包含一个 ManagerId 字段,该字段具有指向 Employee's Id 字段的外键。当我将表作为实体添加到实体数据模型时,它会创建带有 EmployeeChildren 集合元素和 EmployeeParent 元素的新 Employee 实体。我可以检索所有员工并将它们完美地放入 Employee 实体的新实例中。员工实体将有许多子实体,每个子实体可以有许多自己的子实体,并且每个子实体都有一个指向其父实体的指针。

我现在需要做的是使用存储过程检索这些员工的子集。现在,如果我搜索员工 John Doe,他的上方有 2 个人,存储过程将返回 3 行。

EmployeeID ManagerId Name

1 null Bill

2 1 Jane

3 2 John Doe

这是我执行检索的代码:

using (var entity = new TimeEntryEntities())
    {

         var employees =
                 from E in entity.EmployeeSearch(search)
                 orderby E.Name
                 select E;


         return employees.ToList<Employee>();
    }

现在,此代码返回 3 个单独的实体。我怎样才能将它们组合在一起?

I can't quite figure this out. I have a table called Employee with and Id field. The table also contains a ManagerId field which has a foreign key pointing to the Employee's Id field. When I add the table as an entity to my entity data model it creates the new Employee entity with an EmployeeChildren collection element and an EmployeeParent element. I can retrieve all employee's and have them put into a new instance of the Employee entity perfect. The employee entity will have many children, each child entity can have many children of their own and each one has a pointer back to it's parent.

What I need to do now is retrieve a subset of those employee's using a stored procedure. Right now, if I search for employee John Doe, who has 2 people above him, the stored procedure will return 3 rows.

EmployeeID ManagerId Name

1 null Bill

2 1 Jane

3 2 John Doe

Here is my code to do the retrieval:

using (var entity = new TimeEntryEntities())
    {

         var employees =
                 from E in entity.EmployeeSearch(search)
                 orderby E.Name
                 select E;


         return employees.ToList<Employee>();
    }

Right now, this code returns 3 separate entities. How can I have it group them together into one?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

揽月 2024-08-09 14:57:27

听起来您正试图展平层次结构,因此只返回一条记录。也许存储过程中的通用表表达式 (CTE) 可以提供帮助:
这是一个替代方案类似的请求

还有另一个更详细的示例(但您必须免费注册):

It sound like you are trying to flatten out the hierarchy so only one record is returned. Maybe Common Table Expression (CTE) in the stored procedure can help:
Here is an alternate of a similar request:

Also another example with more detail (but you have to register for free):

指尖上的星空 2024-08-09 14:57:27

您应该仅返回您感兴趣的实体。EF 将自动为您检索相关实体。
如果您不使用自我引用,这会更容易可视化,这个概念已经成为障碍。

You should return only the entity you're interested in. EF will retrieve the related entities automatically for you.
This would be easier to visualize if you we're not using a self-reference, this concept has got in the way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文