从Product类返回列表类型

时间:2013-12-11 21:09:24

标签: c# asp.net-mvc asp.net-mvc-4

我在此文件中有一个Product类: Libraries \ Nop.Core \ Domain \ Catalog \ Product.cs

public partial class Product : BaseEntity
{
    public int ProductTypeId { get; set; }
    // 30 more fields, etc.

我在控制器中有一个方法: Admin \ Controllers \ ProductController.cs

public ActionResult ExportExcelAll()
{
    // need to implement this:
    var products = new List<Product>();
    products = ???????

    byte[] bytes = null;
    using (var stream = new MemoryStream())
    {
        _exportManager.ExportProductsToXlsx(stream, products);
        bytes = stream.ToArray();
    }

    return File(bytes, "text/xls", "products.xlsx");
    // PRODUCES AN EXCEL FILE
}

使用该Product类,我想写下这个查询:

select Sku Price from product 

但是...查询的结果必须以List<Product>类型返回:

var products = new List<Product>();

可以通过在Product类中编写一个方法来完成吗?

1 个答案:

答案 0 :(得分:0)

如果你正在使用MVC和Entity Framework并让Visual Studio为你做所有的脚手架,那么你的控制器顶部会有以下内容:

public class MyController : Controller
{
    private MyDataContext db = new MyDataContext();

然后查询您的操作:

var listOfProducts = (from p in db.Products
                     where p.Property == "condition"
                     select p).ToList();

如果您是Linq的新手,我建议您下载LinqPad并运行所提供的教程。此外,它在玩代码时是一个非常宝贵的工具!

相关问题