0

Этот запрос компилируется без ошибок:Не может неявно преобразовать тип 'System.Collections.Generic.List <AnonymousType # 1>' на 'System.Linq.IQueryable <AnonymousType # 2>'

  var _entityList = context.customer 

       .Join(context.applications, 
       cust => cust.cust_id, 
       app => app.cust_id, 
       (cust, app) => new { customer = cust, application = app }) 

       .Join(context.advices, 
       cust => cust.application.app_id, 
       sa => sa.app_id, 
       (cust, sa) => new { customer = cust, advice = sa }) 

       .GroupBy(g => new { g.customer.customer.cust_id, g.customer.customer.cust_code, g.customer.customer.cust_name }) 
       .Select(g => new { cust_id = g.Key.cust_id, cust_code = g.Key.cust_code, cust_name = g.Key.cust_name }) 
       .ToList(); 

While добавив условное где положение с вышеприведенными возвращений запроса времени компиляции ошибка преобразования типа:

  var _entityList = context.customer 

       .Join(context.applications, 
       cust => cust.cust_id, 
       app => app.cust_id, 
       (cust, app) => new { customer = cust, application = app }) 

       .Join(context.advices, 
       cust => cust.application.app_id, 
       sa => sa.app_id, 
       (cust, sa) => new { customer = cust, advice = sa }); 

      if (custcode != null && custcode != "") 
       _entityList = _entityList.Where(e => e.customer.customer.cust_code == custcode); 

      _entityList = _entityList 
       .GroupBy(g => new { g.customer.customer.cust_id, g.customer.customer.cust_code, g.customer.customer.cust_name }) 
       .Select(g => new { cust_id = g.Key.cust_id, cust_code = g.Key.cust_code, cust_name = g.Key.cust_name }) 
       .ToList(); // error on this line 

не может неявно преобразовать тип System.Collections.Generic.List<AnonymousType#1> в System.Linq.IQueryable<AnonymousType#2>

Что мне не хватает?

+0

Вы уверены, что e.customer.customer.cust_code и custcode оба нормальные струны? – Marcus

+0

_entityListis типа IQueryable, и вы пытаетесь назначить в List? – Ehsan

+0

Я бы предложил вам создать класс типа и использовать его в ваших выборках –

ответ

1

Рассмотрим следующий упрощенный пример кода:

var _entityList = Enumerable.Range(0, 1) 
    .Select(i=>new {i1 =i, i2 = i+1}); 
_entityList = _entityList 
    //.Select(i => new { i1 = i.i1, i2 = i.i2 }) // works 
    //.Select(i => i)        // works 
    .Select(i => new { i })       // fails 
    .ToList(); 

В вашем первом сценарии, есть только один анонимный тип вовлечен, следовательно _entityList является List<AnonymousType#1>. В вашей 2-й сценарий, вы изменяете возвращаемый тип из одного анонимного типа:

new { 
    customer = cust, 
    advice = sa 
} 

к другому:

new { 
    cust_id = g.Key.cust_id, 
    cust_code = g.Key.cust_code, 
    cust_name = g.Key.cust_name 
} 

так происходит ошибка преобразования.

Попробуйте это:

var _entityList = context.customer 
    .Join(context.applications, 
      cust => cust.cust_id, 
      app => app.cust_id, 
      (cust, app) => new { customer = cust, application = app }) 
    .Join(context.advices, 
      cust => cust.application.app_id, 
      sa => sa.app_id, 
      (cust, sa) => new { customer = cust, advice = sa }) 
    .Where(e => (custcode != null && custcode != "") 
     ? e.customer.customer.cust_code == custcode : true) 
    .GroupBy(g => new { 
     g.customer.customer.cust_id, 
     g.customer.customer.cust_code, 
     g.customer.customer.cust_name }) 
    .Select(g => new { 
     cust_id = g.Key.cust_id, 
     cust_code = g.Key.cust_code, 
     cust_name = g.Key.cust_name }) 
    .ToList(); 
+0

Итак, как обойти эту проблему?Ваш упрощенный образец кажется просто иллюстрацией проблемы. Не так ли? –

+0

@ Ali.NET, см. Мой обновленный ответ. –

+1

Спасибо. Он работал, а также улучшал подход. –

0

Когда вы наносите Когда пункт используется тип

(cust, sa) => new { customer = cust, advice = sa }. 

Но после того, как вы смените

new { cust_id = g.Key.cust_id, cust_code = g.Key.cust_code, cust_name = g.Key.cust_name } 

Это разные типы компилятора.

+0

Итак, как это можно решить? –

+0

Это зависит от того, что вы хотите. Возможно, примените это место перед списком ToList(). Что-то вроде этого '.Where (e => e.cust_code == custcode)' Я думаю, что сработает. –

+0

Это не сработало. Фактически, он по-прежнему возвращает ошибку после удаления условного условия, где в целом. Тем не менее, я должен попробовать другие предложения. –

1

Изменить

_entityList = _entityList 
      .GroupBy(g => new { g.customer.customer.cust_id, g.customer.customer.cust_code, g.customer.customer.cust_name }) 
      .Select(g => new { cust_id = g.Key.cust_id, cust_code = g.Key.cust_code, cust_name = g.Key.cust_name }) 
      .ToList(); // error on this line 

в

var result = _entityList 
      .GroupBy(g => new { g.customer.customer.cust_id, g.customer.customer.cust_code, g.customer.customer.cust_name }) 
      .Select(g => new { cust_id = g.Key.cust_id, cust_code = g.Key.cust_code, cust_name = g.Key.cust_name }) 
      .ToList(); 
+1

О, я только что получил его. это сработало. Благодарю. –

Смежные вопросы

 Смежные вопросы