2015-03-12 5 views
0

Кто-нибудь знает, почему я получаю эту ошибку при попытке редактировать что-то в базе данных через класс ForestLogisticBEAN?Невозможно неявно преобразовать тип 'System.Collections.Generic.List error

Не может неявно преобразовать тип «System.Collections.Generic.List в 'System.Linq.IQueryable'. Явное преобразование существует (вы пропали без вести бросок?)

Вот интеграция слой:

public void EditParcelDetail(ForestLogisticBEAN parcel){ 

    IQueryable<ForestLogisticBEAN> _ForestLogisticsBeans; 

    _ForestLogisticsBeans = (from order in _context.Orders 
       from tracking in _context.Trackings 
       where order.CustomerID == parcel.Id 
       where tracking.CustomerId == parcel.Id 
       select new {order.DeliveryDate, order.OrderDate, tracking.Status}).ToList(); 
     } 

Вот ForestLogisticBEAN класс:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ForestLogistic.Data.BEANS 
{ 
    public class ForestLogisticBEAN 
    { 

     public int TrackingId { get; set; } 
     public int OrderId { get; set; } 
     public bool Status { get; set; } 
     public DateTime OrderDate { get; set; } 
     public DateTime DeliveryDate { get; set; } 

     public ForestLogisticBEAN() { } 
    } 
} 

UPDATE: Я изменил это вместо списка IQueryable, но теперь вместо этой ошибки выбрасывается

модель элемент передается в словарь типа 'System.Collections.Generic.List`1 [ForestLogistics.Data.BEANS.ForestLogisticBEAN], но этот словарь требует модель элемента типа «ForestLogistics.Data .Порядок'.

Вот новая интеграция слой:

public void EditParcelDetail(ForestLogisticBEAN parcel) 

     { 

       List<ForestLogisticBEAN> _ForestLogisticsBeans; 

       _ForestLogisticsBeans = (from order in _context.Orders 
           from tracking in _context.Trackings 

           where order.CustomerID == parcel.Id 
           where tracking.CustomerId == parcel.Id 
           select new ForestLogisticBEAN { 
            DeliveryDate = parcel.DeliveryDate, 
            OrderDate = parcel.OrderDate, 
            Status = parcel.Status 

           }); 

       _context.SaveChanges(); 

      } 

Цель состоит в том, чтобы иметь возможность совместить заказ и таблицу отслеживания с классом бина

+1

Почему вы объявим его как '' IQueryable вместо 'Список ' или '' IEnumerable ? –

+0

Почему бы не использовать var? 'var _ForestLogisticsBeans = (из заказа в _context.Orders ....' –

ответ

2

Enumerable.ToList возвращает List<T>, который реализует IEnumerable<T> и не IQueryable<T>. Поэтому вы не можете назначить его переменной IQueryable<ForestLogisticBEAN>.

Так почему бы вам не объявить его как список или IEnumerable?

IEnumerable<ForestLogisticBEAN> _ForestLogisticsBeans; 

Вы также должны создавать экземпляры ForestLogisticBEAN вместо anyonymous типа, который вы выбираете. Например:

_ForestLogisticsBeans = (from order in _context.Orders 
         from tracking in _context.Trackings 
         where order.CustomerID == parcel.Id 
         where tracking.CustomerId == parcel.Id 
         select new ForestLogisticBEAN { 
          Status = tracking.Status, 
          OrderDate = order.OrderDate, 
          DeliveryDate = order.DeliveryDate 
         }).ToList(); 
+0

Я обновил его с вашими рекомендациями, но теперь я получаю еще одну ошибку 'Элемент модели, переданный в словарь, имеет тип' System.Collections.Generic.List '1 [ForestLogistics.Data.BEANS.ForestLogisticBEAN] ', но для этого словаря требуется элемент модели типа« ForestLogistics.Data.Order ».' –

+0

@RonS: я не знаком с MVC. Но кажется, что вы используете неправильный тип для вашей модели. Поэтому вместо 'BEANS.ForestLogisticBEAN' используйте' Data.Order'. –

0

Это понятно.

Определение:

IEnumerable<ForestLogisticBEAN> _ForestLogisticsBeans; 

или

List<ForestLogisticBEAN> _ForestLogisticsBeans; 
0

Почему вы определяете _ForestLogisticsBeans как IQueryable<ForestLogisticBEAN>? Вы определили его как IQueryable, и вы назначаете List Он всегда дает вам ошибку.

попробовать var _ForestLogisticsBeans = (from order in _context.Orders....

Или используйте

IEnumerable<ForestLogisticBEAN> _ForestLogisticsBeans; 

Или

List<ForestLogisticBEAN> _ForestLogisticsBeans; 
Смежные вопросы