实体框架 - 以编程方式将 Includes 添加到 ObjectQuery
我有一个实体框架模型,其中有一个具有以下关系的用户:
User 1-* Test
每个测试都有以下关系:
Test 1-1 Course
Test 1-* TestEvent
我有一个返回用户的服务,并且在我的应用程序中的不同点我想急切地获取各种关系。我目前正在获取所有关系:
var result = (from appUser in context.AppUsers.Include("Tests.Course")
.Include("Tests.TestEvents")
where appUser.Login.ToLower() == loginName.ToLower() &&
appUser.IsDeleted == false
select appUser).FirstOrDefault();
我不想总是返回链接到测试或测试事件的课程。如何构建 ObjectQuery 并根据需要动态添加 Include 语句,而不是使用一系列 if else 语句。
I have a Entity Framework model where I have a user which has the following relationships:
User 1-* Test
Each Test has the following relationships:
Test 1-1 Course
Test 1-* TestEvent
I have a service that returns a user and at different points in my application I want to eagerly fetch various relationships. I am fetching all the relationships at present:
var result = (from appUser in context.AppUsers.Include("Tests.Course")
.Include("Tests.TestEvents")
where appUser.Login.ToLower() == loginName.ToLower() &&
appUser.IsDeleted == false
select appUser).FirstOrDefault();
I do not want to always return the Course linked to a Test or the TestEvents. How can I build an ObjectQuery and dynamically add the Include statements as required rather than having a series of if else statements.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,由于
Include
返回一个IQueryable
(LINQ 可链接),我将使用一个简单的扩展方法:然后您的查询如下所示:
要获得一些强类型考虑到 include 的其他魔术字符串性质,我为所有关联都有专门的枚举,因此我传递这些关联的 [] 并将枚举转换为字符串 include。
问题是,您的方法应该定义需要包含哪些内容。因此,您在该方法中要做的第一件事是声明需要哪些关联,然后将其传递给您的扩展方法。
这就是你的追求吗?
Well, since
Include
returns anIQueryable<T>
(LINQ chainable), i would use a simple extension method:Then your query looks like this:
To get some strong-typing into the otherwise magic-string nature of include, i have specialized enums for all associations, so i pass an [] of those through and convert the enum to the string include.
The thing is, your methods should define what inclusions are required. So first thing you do in the method is declare what associations are required, then pass that to your extension method.
Is that what your after?