简体   繁体   English

ASP.NET 铁芯返回

[英]ASP.NET Core Returning

I am using Microsoft Northwind example database.我正在使用 Microsoft Northwind 示例数据库。 I scaffolded the database and everything works besides this code below我搭建了数据库,除了下面的代码之外,一切正常

I want to make work this logic:我想让这个逻辑工作:

select * from Products
join Suppliers
   on Products.customer_id = Suppliers.customer_id
where Products.customer_id = 1

My way I tried to make this SQL query in LINQ (No errors in VS 2019):我尝试在 LINQ 中进行此 SQL 查询(VS 2019 中没有错误):

    public async Task<IActionResult> Index()
    {
         var test = await (from ep in _context.Products
                 join e in _context.Suppliers on ep.SupplierId equals e.SupplierId
                 where (e.SupplierId == 1)
                 select new
                 {ep.ProductName,e.CompanyName}).ToListAsync();
    }
    return View(test);

ERROR after starting the project and going to the Index:启动项目并进入索引后出现错误:

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List 1[<>f__AnonymousType1 1[System.String]]', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable`1[DbFirst.Models.Northwind.Products]'. InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List 1[<>f__AnonymousType1 1[System.String]]', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic .IEnumerable`1[DbFirst.Models.Northwind.Products]'。

Just in case, I am saying that this code works well but it's not what I need:以防万一,我说这段代码运行良好,但这不是我需要的:

public async Task<IActionResult> Index()
{
    var test = await _context.Products.Where(x => x.SupplierId == 1).ToListAsync();

    return View(test);
}

David is correct.Your View receives IEnumerable<Product> while your action return the list of anonymous type.大卫是正确的。您的视图接收IEnumerable<Product>而您的操作返回匿名类型列表。

You could create a specific ViewModel for your View:您可以为您的视图创建一个特定的 ViewModel:

public class ProductViewModel
{
    public string ProductName{ get; set; }
    public string CompanyName{ get; set; }
}

Then,modify action code to return List<ProductViewModel>然后,修改动作代码以返回List<ProductViewModel>

public async Task<IActionResult> Index()
{
     var test = await (from ep in _context.Products
             join e in _context.Suppliers on ep.SupplierId equals e.SupplierId
             where (e.SupplierId == 1)

             select new ProductViewModel
             {  
                ep.ProductName,
                e.CompanyName
             }).ToListAsync();
}
return View(test);

Finally,modify @model of Index View:最后,修改索引视图的@model

@model IEnumerable<ProductViewModel>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM