EF6:使用具有IQueryable的引用/查找数据

本文关键字:引用 查找 数据 IQueryable EF6 | 更新日期: 2023-09-27 18:23:58

我想在查询中使用来自列表的预加载查找数据。我需要查询返回为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;
    }

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

我想以某种方式告诉EF在SQL或类似内容之后应用查找。我读过关于用EF Helper代码和表达式做类似的事情,但我再也找不到那篇文章了。

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

感谢您的帮助。

EF6:使用具有IQueryable的引用/查找数据

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

这听起来可能很复杂,但实际上并没有那么难实现。需要完成以下操作:

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

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

  3. 编写IQueryProvider<T>InterceptingQueryProvider<T>实现,该实现反过来封装从EF获得的查询提供程序。

  4. 编写IEnumerator<T>InterceptingEnumerator<T>实现,该实现中继到EF返回的枚举器对象此枚举器将在执行MoveNext之后立即注入Status属性的值(可以很容易地通过这种方式泛化以填充任何查找属性),以便完全填充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);
        }
    }
}

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

public partial class Contact
{
    [NotMapped]
    public StatusType Status { get; set; }
}

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

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

打印:

--- SOME CONTACTS ---
1: John Smith, Acme Corp, 3=Status Three
3: Jon Snow, The Wall, 2=Status Two

查询被翻译成:

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

与无法在数据库端处理整个查询的明显缺点相比,我不确定避免联接的好处是什么,但您所要求的可以通过使用Linq-to-Entities尽可能多地进行(过滤、排序、分组、投影)来实现,然后将其转换为IEnumerable,并使用Linq-to-Objects完成其余操作。您可以始终使用Enumerable.AsQueryableIEnumerable上切换到IQueryable实现。像这样的

public IQueryable GetQuery()
{
    var db = new ContactsDbContext();
    var query = db.Contacts.Select(contact => new
    {
        Id = contact.Id,
        FullName = contact.FirstName + " " + contact.LastName,
        CompanyName = contact.CompanyName,
        StatusId = contact.StatusId
    })
    .AsEnumerable()
    .Select(contact => new
    {
        Id = contact.Id,
        FullName = contact.FullName,
        CompanyName = contact.CompanyName,
        Status = _statusTypes.FirstOrDefault(l => contact.StatusId == l.Id).Label
    })
    .AsQueryable();
    return query;
}