我正在使用Microsoft Northwind示例数据库。我搭建了数据库,除了下面的代码,其他所有东西都可以正常工作
我想按以下逻辑工作:
select * from Products
join Suppliers
on Products.customer_id = Suppliers.customer_id
where Products.customer_id = 1
我试图用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);
启动项目并转到索引后出现错误:
InvalidOperationException:传递到ViewDataDictionary的模型项的类型为'System.Collections.Generic.List 1[<>f__AnonymousType1
1 [System.String]]',但是此ViewDataDictionary实例需要类型为'System.Collections.Generic.IEnumerable`1 [ DbFirst.Models.Northwind.Products]”。
以防万一,我是说这段代码很好用,但这不是我所需要的:
public async Task<IActionResult> Index()
{
var test = await _context.Products.Where(x => x.SupplierId == 1).ToListAsync();
return View(test);
}
大卫是正确的。IEnumerable<Product>
您的视图会在您的操作返回匿名类型列表时收到。
您可以为视图创建一个特定的ViewModel:
public class ProductViewModel
{
public string ProductName{ get; set; }
public string CompanyName{ get; set; }
}
然后,修改动作代码以返回 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);
最后,修改@model
索引视图:
@model IEnumerable<ProductViewModel>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句