AsQueryable ()의 목적은 무엇입니까?
그 목적은 AsQueryable()
당신 IEnumerable
이 기대할 수있는 메소드를 전달할 수 있도록 하는 것입니까 IQueryable
, 아니면 다음 IEnumerable
과 같이 표현할 유용한 이유가 IQueryable
있습니까? 예를 들어, 다음과 같은 경우에 해당해야합니까?
IEnumerable<Order> orders = orderRepo.GetAll();
// I don't want to create another method that works on IEnumerable,
// so I convert it here.
CountOrders(orders.AsQueryable());
public static int CountOrders(IQueryable<Order> ordersQuery)
{
return ordersQuery.Count();
}
또는 실제로 다른 작업을 수행합니까?
IEnumerable<Order> orders = orderRepo.GetAll();
IQueryable<Order> ordersQuery = orders.AsQueryable();
IEnumerable<Order> filteredOrders = orders.Where(o => o.CustomerId == 3);
IQueryable<Order> filteredOrdersQuery = ordersQuery.Where(o => o.CustomerId == 3);
// Are these executed in a different way?
int result1 = filteredOrders.Count();
int result2 = filteredOrdersQuery.Count();
IQueryable
이러한 확장 메서드 의 버전은 일단 실행되면 동일한 작업을 수행하는 Expression을 구축합니까? 내 주요 질문은 사용에 대한 실제 사용 사례는 AsQueryable
무엇입니까?
몇 가지 주요 용도가 있습니다.
다른 답변에서 언급했듯이 메모리 내 데이터 소스를 사용하여 쿼리 가능한 데이터 소스를 모의하는 데 사용할 수 있으므로 결국 열거 불가능 기반에서 사용될 메서드를 더 쉽게 테스트 할 수 있습니다
IQueryable
.메모리 내 시퀀스 또는 외부 데이터 소스에 적용 할 수있는 컬렉션을 조작하기위한 도우미 메서드를 작성할 수 있습니다.
IQueryable
완전히 사용할 도움말 메서드를 작성하는 경우AsQueryable
모든 열거 형에 사용하여 사용할 수 있습니다. 이렇게하면 매우 일반화 된 도우미 메서드의 두 가지 개별 버전을 작성하지 않아도됩니다.이를 통해 쿼리 가능의 컴파일 시간 유형을
IQueryable
더 파생 된 유형이 아닌 으로 변경할 수 있습니다 . 사실상; 당신은 그것을 사용하는 거라고IQueryable
당신이 사용하는 거라고 같은 시간에AsEnumerable
온IEnumerable
. 구현하는 객체가있을 수IQueryable
있지만 인스턴스Select
메서드도 있습니다. 이 경우 LINQSelect
메서드 를 사용하려는 경우 개체의 컴파일 시간 유형을IQueryable
. 그냥 캐스팅 할 수 있지만AsQueryable
메서드를 사용하면 유형 추론을 활용할 수 있습니다. 이것은 제네릭 인수 목록이 복잡 할 때 더 편리 하고 제네릭 인수가 익명 유형 인 경우 실제로 필요 합니다.
AsQueryable에 대한 가장 유효한 사례는 단위 테스트입니다. 다음과 같은 다소 인위적인 예가 있다고 가정하십시오.
public interface IWidgetRepository
{
IQueryable<Widget> Retrieve();
}
public class WidgetController
{
public IWidgetRepository WidgetRepository {get; set;}
public IQueryable<Widget> Get()
{
return WidgetRepository.Retrieve();
}
}
컨트롤러가 저장소에서 반환 된 결과를 다시 전달하는지 확인하기 위해 단위 테스트를 작성하고 싶습니다. 다음과 같이 보일 것입니다.
[TestMethod]
public void VerifyRepositoryOutputIsReturned()
{
var widget1 = new Widget();
var widget2 = new Widget();
var listOfWidgets = new List<Widget>() {widget1, widget2};
var widgetRepository = new Mock<IWidgetRepository>();
widgetRepository.Setup(r => r.Retrieve())
.Returns(listOfWidgets.AsQueryable());
var controller = new WidgetController();
controller.WidgetRepository = widgetRepository.Object;
var results = controller.Get();
Assert.AreEqual(2, results.Count());
Assert.IsTrue(results.Contains(widget1));
Assert.IsTrue(results.Contains(widget2));
}
실제로 모든 AsQueryable () 메서드를 사용하면 mock을 설정할 때 컴파일러를 만족시킬 수 있습니다.
그래도 응용 프로그램 코드에서 이것이 사용되는 곳에 관심이 있습니다.
sanjuro가 언급했듯이 AsQueryable ()의 목적은 Using AsQueryable With Linq To Objects And Linq To SQL에 설명되어 있습니다. 특히 기사는 다음과 같이 말합니다.
This offers an excellent benefits in real word scenarios where you have certain methods on an entity that return an IQueryable of T and some methods return List. But then you have business rule filter that needs to be applied on all the collection regardless if the collection is returned as IQueryable of T or IEnumerable of T. From a performance stand point, you really want to leverage executing the business filter on the database if the collection implements IQueryable otherwise fall back to apply the business filter in memory using Linq to object implementation of delegates.
The purpose of AsQueryable() is greatly explained in this article Using AsQueryable With Linq To Objects And Linq To SQL
From Remarks section of MSDN Queryable.AsQueryable Method:
If the type of source implements IQueryable, AsQueryable(IEnumerable) returns it directly. Otherwise, it returns an IQueryable that executes queries by calling the equivalent query operator methods in Enumerable instead of those in Queryable.
Thats is exactly what is mentioned and used in above article. In your example, it depends on what is orderRepo.GetAll returning, IEnumerable or IQueryable(Linq to Sql). If it returns IQueryable, the Count() method will be executed on database otherwise it will be executed in memory. Look carefully at example in referenced article.
Interface IQueryable
quoting documentation:
The IQueryable interface is intended for implementation by query providers.
So for someone that intends to make its datastracture queryable in .NET, that datastructure that not necessary can be enumerated or have valid enumerator.
IEnumerator
is an interface for iterating and processing stream of data instead.
참고URL : https://stackoverflow.com/questions/17366907/what-is-the-purpose-of-asqueryable
'code' 카테고리의 다른 글
왜 C ++에서 파이썬보다 문자열을 더 느리게 분할합니까? (0) | 2020.09.06 |
---|---|
TensorFlow 저장 / 파일에서 그래프로드 (0) | 2020.09.06 |
파이썬 함수를 피클 (또는 코드를 직렬화)하는 쉬운 방법이 있습니까? (0) | 2020.09.05 |
Linux 명령 : 텍스트 파일 만 '찾기'방법은 무엇입니까? (0) | 2020.09.05 |
Jquery 바인딩 두 번 클릭과 단일 클릭을 별도로 (0) | 2020.09.05 |