![](/img/trans.png)
[英]LINQ to SQL doesn't return data, but the generated SQL statement does
[英]LINQ to SQL return statement
在一个项目中,我有一个LINQ to SQL类,即OrderingSystem.dbml。 我有以下代码,在select语句中,我只想从每个表中检索某些行(产品-类别)。 但是,当然,我现在拥有的return语句是不正确的。 使用正确的return语句是什么? 提前致谢
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();
}
如果要检索产品列表,则必须在“选择新的”上指定类型,现在它会创建一个匿名类型。 尝试更改:
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();
}
您的返回类型为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;
这是因为在LINQ表达式中,您做了一个select new { }
,它创建了一个匿名对象,而您的方法返回了一个List of Product
。 您应该更改select
语句,使其变为select new Product() { ProductName = p.ProductName, ...
,其余内容取决于Product
类的结构。
通过使用“选择新” LINQ操作,您正在创建匿名类型。 您可以在对象创建的当前范围内访问该匿名类型的属性,但是不能使用任何可识别的类型返回该匿名类型。 您有两种选择:
List<object>
返回集合。 如果这样做,您仍然可以从对象中检索值,但是您将需要通过反射来进行检索。 如果将集合用作数据绑定方案中的数据源,则这可能非常有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.