gpt4 book ai didi

c# - 在 ASP.NET MVC 中传递匿名类型

转载 作者:行者123 更新时间:2023-11-30 19:34:46 25 4
gpt4 key购买 nike

我在 C# 中使用 ASP.net MVC。为什么这是代码:

public IQueryable<Product> ListProducts(string prodcutType)
{
var results = from p in db.Products
join s in db.Stocks
on p.ID equals s.IDProduct
where p.ptype == prodcutType
select new { s.width, s.height, s.number};
return results;
}

显示以下错误?

Error 1 Cannot implicitly convert type System.Linq.IQueryable<AnonymousType#1> to System.Linq.IQueryable<eim.Models.Product>. An explicit conversion exists (are you missing a cast?)

最佳答案

因为 select new { s.width, s.height, s.number}表示 System.Linq.IQueryable<AnonymousType#1>但是你的函数期望返回 IQueryable<Product> .将您的代码更改为:

public IQueryable<Product> ListProducts(string prodcutType)
{

var results = from p in db.Products
join s in db.Stocks
on p.ID equals s.IDProduct
where p.ptype == prodcutType
select p;
return results;
}

更新:

或者您可能需要 IQueryable<Stock> :

public IQueryable<Stock> ListProducts(string prodcutType)
{

var results = from p in db.Products
join s in db.Stocks
on p.ID equals s.IDProduct
where p.ptype == prodcutType
select s;
return results;
}

如果你只想要 3 个属性 width+height+number 创建新类型。例如:

public class SomeType {
public int Width { get; set; }
public int Height { get; set; }
public int Number { get; set; }
}

public IQueryable<SomeType> ListProducts(string prodcutType)
{

var results = from p in db.Products
join s in db.Stocks
on p.ID equals s.IDProduct
where p.ptype == prodcutType
select new SomeType {
Width = s.width,
Height = s.height,
Number = s.number
};
return results;
}

关于c# - 在 ASP.NET MVC 中传递匿名类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1100372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com