无法将List <model>转换为model </model>

时间:2013-12-16 14:36:05

标签: c# linq entity-framework model

我的代码存在一些问题,它在3个表之间有多对多,我使用LINQ实体,首先我对引用ID进行分组,然后使用id从每个表中获取信息并尝试将其放入viewmodel ,我不确定我的情况是否正确

对于多个商品,应该有一个多个供应商的多个价格报价,商品名称必须在列中,价格必须在下面。

无论如何,下面的问题是

Error   3   The best overloaded method match for 
System.Collections.Generic.List<ITAPP.Models.tblQuotes>.Add(ITAPP.Models.tblQuotes)
has some invalid arguments  PurchasingController.cs 48  17  ITAPP`

Error   4   Argument 1: cannot convert from             
System.Collections.Generic.List<ITAPP.Models.tblQuotes>' to 'ITAPP.Models.tblQuotes'  
PurchasingController.cs 48  37  ITAPP`

这是代码

var tblQuoting =
    from d in db.Quotes_Items_Suppliers 
    group d by new
    {
        d.QuoteID
    } into g
    select new {
        QuoteID = g.Key
    };

var model = new List<QuoteViewModel>();
foreach (var Quotes in tblQuoting)
{

    var ModelItem = new QuoteViewModel();

    ModelItem.Quote = new List<tblQuotes>();
    ModelItem.Suppliers = new List<tblSuppliers>();
    ModelItem.Items = new List<tblItems>();
    ModelItem.Prices = new List<tblQuotes_Items_Suppliers>();

    //Add the quote info to model
    int QuoteID = Convert.ToInt32(Quotes.QuoteID);
    var Quote = (from d in db.Quotes
                    where d.ID == QuoteID
                    select d).ToList();

    ModelItem.Quote.Add(Quote);

    //add all the suppliers to the quote model
    var Suppliers = (from d in db.Quotes_Items_Suppliers.Include(t => t.tblSuppliers)
                        where d.QuoteID == QuoteID
                        select d).ToList();
    ModelItem.Suppliers.Add(Suppliers);

    //add the items to the quote model
    var Items = (from d in db.Quotes_Items_Suppliers.Include(t => t.tblItems)
                        where d.QuoteID == QuoteID
                        select d).ToList();
    ModelItem.Items.Add(Items);

    model.Add(ModelItem);
}
return View("Index", model);

这是我的模特(如果是的话?)

public class QuoteViewModel
{
    public List<tblQuotes> Quote { get; set; }
    public List<tblSuppliers> Suppliers { get; set; }
    public List<tblItems> Items { get; set; }
    public List<tblQuotes_Items_Suppliers> Prices { get; set; }
}

索引

1 个答案:

答案 0 :(得分:2)

使用AddRange将项目序列添加到列表中:

ModelItem.Quote.AddRange(Quote);
ModelItem.Suppliers.AddRange(Suppliers);
ModelItem.Items.AddRange(Items);

或者只是在没有初始化的情况下分配列表(因此您将避免创建中间列表并将项目从一个列表复制到另一个列表):

ModelItem.Quote = Quote;
ModelItem.Suppliers = Supplies;
ModelItem.Items = Items;

甚至使用object initalizer:

 var ModelItem = new QuoteViewModel {
      Quote = db.Quotes.Where(q => q.ID == QuoteID).ToList(),
      Suppliers = db.Quotes_Items_Suppliers.Include(t => t.tblSuppliers)
                    .Where(s => s.QuoteID == QuoteID).ToList(),
      Items = db.Quotes_Items_Suppliers.Include(t => t.tblItems)
                .Where(i => i.QuoteID == QuoteID).ToList()
 };