在一个项目中,我有一个LINQ to SQL类,它是OrderingSystem.dbml。我有以下代码,在select语句中,我只想从每个表中检索一些行(Products- Categories)。当然,我现在得到的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();
}发布于 2012-01-24 08:31:21
在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();
}发布于 2012-01-24 08:32:15
您的返回类型是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;发布于 2012-01-24 08:32:49
这是因为在LINQ表达式中,你做了一个创建匿名对象的select new { },而你的方法返回一个Product列表。您应该更改select语句,使其变为select new Product() { ProductName = p.ProductName, ...,其余的取决于您的Product类的结构。
https://stackoverflow.com/questions/8980545
复制相似问题