LINQ to SQL返回语句

本文关键字:语句 返回 SQL to LINQ | 更新日期: 2023-09-27 18:21:07

在一个项目中,我有一个LINQ to SQL类,它是OrderingSystem.dbml。我有以下代码,在select语句中,我只想从每个表中检索一些行(Products-Categories)。当然,我现在的回报声明是不正确的。要使用的正确返回语句是什么??提前感谢


    OrderingSystemDataContext database = new OrderingSystemDataContext();
    public List<Product> GetProductsByCategoryID(int CategoryID)
    {
        var result = from p in database.Products
        join c in database.Categories
        on p.CategoryID equals c.CategoryID
        where p.CategoryID == CategoryID
        select new { p.ProductName, p.ProductPrice, p.ProductDescription, c.CategoryName };
        //This is not working
        return result.ToList();
    }

LINQ to SQL返回语句

在select new上,如果您想要检索产品列表,则必须指定类型,现在它会创建一个匿名类型。尝试更改:

OrderingSystemDataContext database = new OrderingSystemDataContext();
public List<Product> GetProductsByCategoryID(int CategoryID)
{
    var result = from p in database.Products
    join c in database.Categories
    on p.CategoryID equals c.CategoryID
    where p.CategoryID == CategoryID
    //Assuming that these are the names of your properties
    select new Product(){ProductName = p.ProductName, ProductPrice = p.ProductPrice, ProductDescription = p.ProductDescription, CategoryName = c.CategoryName };
    return result.ToList();
}

这是因为在LINQ表达式中,您执行了创建匿名对象的select new { },而您的方法返回了Product的列表。您应该更改select语句,使其成为select new Product() { ProductName = p.ProductName, ...,其余部分取决于Product类的结构。

通过使用"select new"LINQ操作,您正在创建一个匿名类型。您可以在对象创建的当前范围内访问该匿名类型的属性,但不能使用任何类型的可识别类型返回该匿名类型。你有两个选择:

  1. 创建一个新类(例如Product)并创建该类型的实例,作为选择语句的一部分(如其他答案所示)
  2. 将集合返回为List<object>。如果这样做,仍然可以从对象中检索值,但需要通过反射来检索。如果在数据绑定场景中使用集合作为数据源,这可能非常有效

您的返回类型是Product,但查询结果使用匿名类型。

更改此行:

select new { p.ProductName, p.ProductPrice, p.ProductDescription, c.CategoryName };

类似的东西:

select new Product { Name = p.ProductName, Price = p.ProductPrice, Description = p.ProductDescription, Category = c.CategoryName };

编辑:

尝试将其替换为:

select p;