2012-08-27 3 views
1
를 인식하지 못합니다

아래의 코드 오류 발생 :LINQ는 사용자 정의 방법

LINQ to Entities does not recognize the method System.String GenerateSubscriptionButton(Int32) method, and this method cannot be translated into a store expression.

가 어떻게 엔티티에 LINQ에서 올바른 사용자 정의 메소드를 만들려면 어떻게해야합니까를?

var model = _serviceRepository.GetProducts().Select(p => new ProductModel 
{ 
    Id = p.Id, 
    Name = p.Name, 
    Credits = p.Credits, 
    Months = p.Months, 
    Price = p.Price, 
    PayPalButton = GenerateSubscriptionButton(p.Id) 
});   

private string GenerateSubscriptionButton(int id) 
{ 
    return new PaymentProcessor.PayPalProcessor().CreateSubscriptionButton(id); 
} 

답변

5

당신은 그렇게 할 수 없습니다. 공급자가 귀하의 방법을 SQL로 어떻게 변환해야합니까?

기억하십시오 : LINQ to Entities는 실제로 쿼리의 C# 코드를 실행하지 않습니다. 대신 표현식을 해석하고이를 표현식으로 변환합니다. 당신의 conrete 경우

이 솔루션은 아마도 다음과 같을 것이다 :

var model = _serviceRepository.GetProducts() 
           .Select(p => new ProductModel 
              { 
               Id = p.Id, 
               Name = p.Name, 
               Credits = p.Credits, 
               Months = p.Months, 
               Price = p.Price 
              }) 
           .ToList() 
           .Select(x => 
             { 
              x.PayPalButton = GenerateSubscriptionButton(x.Id); 
              return x; 
             }); 

ToList에 대한 호출은 지금까지 데이터베이스에 대해 쿼리를 실행하고 결과를 반환합니다. 이 시점에서 쿼리는 실제로 코드가 해석되지 않고 실행되는 개체 쿼리에 대한 LINQ입니다.

+0

감사합니다.이 답변은 내 하루를 만들었습니다. :) – NMathur

1

수 없습니다. 문제는 SQL에서 GenerateSubscriptionButton으로 호출 할 수 없다는 것입니다.

엔티티를 가져와야하고 메모리에 저장되면 GenerateSubscriptionButton을 호출 할 수 있습니다. 모델에 엔티티를 투영하기 전에 AsEnumerable에 대한 호출을 추가하면됩니다.

var model = _serviceRepository.GetProducts() 
    .AsEnumerable() 
    .Select(p => new ProductModel 
        { 
         Id = p.Id, 
         Name = p.Name, 
         Credits = p.Credits, 
         Months = p.Months, 
         Price = p.Price, 
         PayPalButton = GenerateSubscriptionButton(p.Id) 
        });