2014-09-02 8 views
5

मैं इकाई फ्रेमवर्क का उपयोग कर विभिन्न तालिकाओं तक पहुंचने के लिए तर्क को मजबूत करने की कोशिश कर रहा हूं। मैं अपने पंजीकरण इकाई से सभी पंजीकरण खींचने के लिए, जहां व्यक्ति भाग ले रहे एक विस्तार विधि बनाया:क्या मैं इकाई फ्रेमवर्क सबक्वियर में एक विस्तार विधि का उपयोग कर सकता हूं?

public static IEnumerable<Registration> Attending(this IEnumerable<Registration> registrations) 
{ 
    return registrations.Where(r => r.Status == RegistrationStatus.Paid || r.Status == RegistrationStatus.Assigned || r.Status == RegistrationStatus.Completed); 
} 

यह इस तरह के प्रश्नों के लिए महान काम करता है:

var attendees = db.Registrations.Attending().ToList(); 

लेकिन जब में इस्तेमाल किया यह काम नहीं करता एक सबक्वेरी:

ProductTotals = db.Products.Where(p => p.EventID == ev.Id).Select(p => new ProductSummaryViewModel 
{ 
    ProductID = p.ProductID, 
    ProductName = p.Name, 
    Registrations = p.Registrations.Attending().Count(), 
}).ToList(); 

मैं निम्नलिखित त्रुटि मिलती है:

LINQ to Entities does not recognize the method 'System.Collections.Generic.IEnumerable 1[Registration] Attending(System.Collections.Generic.IEnumerable 1[Registration])' method, and this method cannot be translated into a store expression.

क्या कोई कोड उस सबक्यूरी में फिर से उपयोग करने का कोई तरीका है?

+0

आप मेमोरी में ऑपरेशन करने के लिए 'select' से पहले 'AsEnumerable()' का उपयोग कर सकते हैं। हालांकि आप इसे डेटाबेस स्तर पर करने के फायदे खो देते हैं। – Shoe

+2

यदि आप इसे ईएफ प्रश्नों पर उपयोग कर रहे हैं, तो उस विधि को 'IQueryable' को 'IUumerable'' स्वीकार नहीं करना चाहिए और अन्यथा डेटाबेस पर क्वेरी नहीं की जा रही है। – Servy

+0

@ सर्वी धन्यवाद, मैंने वही बात देखी और IQueryable का उपयोग करने के लिए इसे बदल दिया – Austin

उत्तर

8

मुख्य चीज जिसे आप प्राप्त करने का प्रयास कर रहे हैं वह भविष्यवाणी का पुन: उपयोग कर रहा है जो Attending के अर्थ को परिभाषित करता है। आप अभिव्यक्ति को एक रीडोनली वैरिएबल में संग्रहीत करके कर सकते हैं जो किसी भी व्यक्ति को आपके एप्लिकेशन में इसकी आवश्यकता होती है, उदाहरण के लिए एक स्थिर वर्ग ExpressionConstants में।

public static readonly Expression<Func<Registration, bool>> IsAttending = 
    r => r.Status == RegistrationStatus.Paid 
     || r.Status == RegistrationStatus.Assigned 
     || r.Status == RegistrationStatus.Completed; 

तो फिर तुम क्या कर सकते हैं

var attendees = db.Registrations.Where(ExpressionConstants.IsAttending).ToList(); 

और सबक्वेरी में इस्तेमाल किया:

ProductTotals = db.Products.Where(p => p.EventID == ev.Id).Select(p => new ProductSummaryViewModel 
{ 
    ProductID = p.ProductID, 
    ProductName = p.Name, 
    Registrations = p.Registrations.AsQueryable() // AsQueryable() 
        .Where(ExpressionConstants.IsAttending).Count(), 
}) 

AsQueryable() आवश्यक है, क्योंकि p.Registrations शायद एक ICollection है।

संबंधित मुद्दे

 संबंधित मुद्दे