实体框架 - 程序地添加包含ObjectQuery [英] Entity Framework - Programatically add Includes to ObjectQuery

查看:103
本文介绍了实体框架 - 程序地添加包含ObjectQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体框架模型,我有一个用户具有以下关系:

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();

我不想总是返回与Test或TestEvent相关联的课程。如何构建ObjectQuery并根据需要动态添加Include语句,而不是使用一系列if else语句。

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.

推荐答案

,因为 Include 返回一个 IQueryable< T> (LINQ chainable),我将使用一个简单的扩展方法: p>

Well, since Include returns an IQueryable<T> (LINQ chainable), i would use a simple extension method:

public static IQueryable<T> WithIncludes<T>(this IQueryable<T> source, string[] associations)
{
   var query = (ObjectQuery<T>)source;

   foreach (var assoc in associations)
   {
      query = query.Include(assoc);
   }
}

然后你的查询如下所示:

Then your query looks like this:

var inclusions = new[] { "Tests.Course", "Tests.TestEvents" };
var result = ctx.AppUsers
                .WithIncludes(inclusions)
                .Where(x => x.Login.ToLower() == loginName.ToLower())
                .Where(x => !x.IsDeleted)
                .FirstOrDefault();

为了获得一些强大的打字到包含的其他魔术字符串的性质,我有专门的枚举所有的协会,所以我通过一个[]通过并将枚举转换为字符串include。

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.

这是你以后的什么?

这篇关于实体框架 - 程序地添加包含ObjectQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆