EF6:通过 IQueryable 使用参考/查找数据

Ste*_*yon 5 c# linq lookup iqueryable entity-framework-6

我想在查询中使用列表中预加载的查找数据。我需要查询作为 IQueryable 返回,因为它在网格中使用并被分页(此处不包括)。我需要从查找中加载标签以避免连接(更多内容在实际代码中)。

我知道我可以执行 ToList() 并对其进行后处理,但我需要 IQueryable。这是代码:

// Run in intialization other code...
var contactLookups = new ContactsDbContext();
List<StatusType> _statusTypes = contactLookups.StatusTypes.ToList();


    public IQueryable GetQuery()
    {
        var contactsCtx = new ContactsDbContext();
        IQueryable query = contactsCtx.Select(contact => new
        {
            Id = contact.Id,
            FullName = contact.FirstName + " " + contact.LastName,
            CompanyName = contact.CompanyName,
            Status = _statusTypes.FirstOrDefault(l => contact.StatusId == l.Id).Label
        });
        return query;
    }
Run Code Online (Sandbox Code Playgroud)

上面的代码会引发错误,因为 EF/LINQ 无法将内存中的列表形成为 SQL(出于明显的原因)——除非添加/更改了某些内容。

我想以某种方式告诉 EF 在 SQL 之后应用查找或达到此效果。我读过有关使用 EF Helper 代码和表达式执行类似操作的内容,但我找不到那篇文章了。

请注意,我对查找本身很灵活。唯一不可协商的是“contact.StatusId”(int),但结构的其余部分“_statusTypes.FirstOrDefault(l => contact.StatusId == l.Id)”与List类型一样,是开放的。

任何帮助表示赞赏。

fel*_*x-b 3

您可以将 EF 的查询包装到您自己的 IQueryable 拦截实现中,其中您可以在将对象返回到应用程序之前注入内存中查找的值。

听起来可能很复杂,但实际上实施起来并不难。需要完成以下工作:

  1. 将实体中的属性标记Status为非映射(Ignore()与 Fluent API 或[NotMapped]属性上的属性一起使用)。

  2. 编写InterceptingQueryable<T>(我们这样命名) 的实现IOrderedQueryable<T>,它包装IQueryable<T>来自 EF 的对象(由示例中的 Select 方法返回)。

  3. 编写InterceptingQueryProvider<T>的实现IQueryProvider<T>,它又包装从 EF 获取的查询提供程序。

  4. 编写InterceptingEnumerator<T>的实现IEnumerator<T>,它中继到 EF 返回的枚举器对象。该枚举器将在执行后立即注入 Status 属性的值(可以轻松地概括为以这种方式填充任何查找属性) ,以便完全填充MoveNext返回的对象。Current

上面的链连接如下:

  1. InterceptingQueryable中继到 EF 的查询对象,并在构造函数中传递。

  2. InterceptingQueryable.Provider财产回报InterceptingQueryProvider。

  3. InterceptingQueryable.GetEnumerator方法返回InterceptingEnumerator.

  4. InterceptingQueryProvider.CreateQuery方法从 EF 查询提供程序获取查询对象,然后将其包装在另一个 InterceptingQueryable.

  5. InterceptingQueryProvider.Execute在 EF 查询提供程序上调用Execute,然后在它获取要进行查找注入的实体的情况下,它会以与之前相同的方式注入查找值InterceptingEnumerator(提取方法以供重用)。

更新

这是代码:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Examples.Queryables
{
    public class InterceptingQueryable<T> : IOrderedQueryable<T>
    {
        private readonly Action<T> _interceptor;
        private readonly IQueryable<T> _underlyingQuery;
        private InterceptingQueryProvider _provider;

        public InterceptingQueryable(Action<T> interceptor, IQueryable<T> underlyingQuery)
        {
            _interceptor = interceptor;
            _underlyingQuery = underlyingQuery;
            _provider = null;
        }
        public IEnumerator<T> GetEnumerator()
        {
            return new InterceptingEnumerator(_interceptor, _underlyingQuery.GetEnumerator());
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
        public Expression Expression 
        {
            get { return _underlyingQuery.Expression; }
        }
        public Type ElementType 
        {
            get { return _underlyingQuery.ElementType; }
        }
        public IQueryProvider Provider 
        {
            get
            {
                if ( _provider == null )
                {
                    _provider = new InterceptingQueryProvider(_interceptor, _underlyingQuery.Provider); 
                }
                return _provider;
            }
        }

        private class InterceptingQueryProvider : IQueryProvider
        {
            private readonly Action<T> _interceptor;
            private readonly IQueryProvider _underlyingQueryProvider;

            public InterceptingQueryProvider(Action<T> interceptor, IQueryProvider underlyingQueryProvider)
            {
                _interceptor = interceptor;
                _underlyingQueryProvider = underlyingQueryProvider;
            }
            public IQueryable CreateQuery(Expression expression)
            {
                throw new NotImplementedException();
            }
            public IQueryable<TElement> CreateQuery<TElement>(Expression expression)
            {
                var query = _underlyingQueryProvider.CreateQuery<TElement>(expression);

                if ( typeof(T).IsAssignableFrom(typeof(TElement)) )
                {
                    return new InterceptingQueryable<TElement>((Action<TElement>)(object)_interceptor, query);
                }
                else
                {
                    return query;
                }
            }
            public object Execute(Expression expression)
            {
                throw new NotImplementedException();
            }
            public TResult Execute<TResult>(Expression expression)
            {
                var result = _underlyingQueryProvider.Execute<TResult>(expression);

                if ( result is T )
                {
                    _interceptor((T)(object)result);
                }

                return result;
            }
        }

        private class InterceptingEnumerator : IEnumerator<T>
        {
            private readonly Action<T> _interceptor;
            private readonly IEnumerator<T> _underlyingEnumerator;
            private bool _hasCurrent;

            public InterceptingEnumerator(Action<T> interceptor, IEnumerator<T> underlyingEnumerator)
            {
                _interceptor = interceptor;
                _underlyingEnumerator = underlyingEnumerator;
                _hasCurrent = false;
            }
            public void Dispose()
            {
                _underlyingEnumerator.Dispose();
            }
            public bool MoveNext()
            {
                _hasCurrent = _underlyingEnumerator.MoveNext();

                if ( _hasCurrent )
                {
                    _interceptor(_underlyingEnumerator.Current);
                }

                return _hasCurrent;
            }
            public void Reset()
            {
                _underlyingEnumerator.Reset();
            }
            public T Current 
            {
                get
                {
                    return _underlyingEnumerator.Current;
                }
            }
            object IEnumerator.Current
            {
                get { return Current; }
            }
        }
    }

    public static class QueryableExtensions
    {
        public static IOrderedQueryable<T> InterceptWith<T>(this IQueryable<T> query, Action<T> interceptor)
        {
            return new InterceptingQueryable<T>(interceptor, query);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是测试用例/示例。首先,我们不应该忘记将非映射的 Status 属性添加到 Contact 实体:

public partial class Contact
{
    [NotMapped]
    public StatusType Status { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后,我们可以使用拦截器机制,如下:

var contactLookups = contactsCtx.StatusTypes.ToList();

Action<Contact> interceptor = contact => {
    contact.Status = contactLookups.FirstOrDefault(l => contact.StatusId == l.Id);
};

// note that we add InterceptWith(...) to entity set
var someContacts = 
    from c in contactsCtx.Contacts.InterceptWith(interceptor) 
    where c.FullName.StartsWith("Jo")
    orderby c.FullName, c.CompanyName
    select c;

Console.WriteLine("--- SOME CONTACTS ---");
foreach ( var c in someContacts )
{
    Console.WriteLine(
        "{0}: {1}, {2}, {3}={4}", 
        c.Id, c.FullName, c.CompanyName, c.StatusId, c.Status.Name);
}
Run Code Online (Sandbox Code Playgroud)

打印:

--- SOME CONTACTS ---
1: John Smith, Acme Corp, 3=Status Three
3: Jon Snow, The Wall, 2=Status Two
Run Code Online (Sandbox Code Playgroud)

查询被翻译成:

SELECT 
    [Extent1].[Id] AS [Id], 
    [Extent1].[FullName] AS [FullName], 
    [Extent1].[CompanyName] AS [CompanyName], 
    [Extent1].[StatusId] AS [StatusId]
    FROM [dbo].[Contacts] AS [Extent1]
    WHERE [Extent1].[FullName] LIKE 'Jo%'
    ORDER BY [Extent1].[FullName] ASC, [Extent1].[CompanyName] ASC
Run Code Online (Sandbox Code Playgroud)