C# 有人能帮我在linq查询下施展吗?
这是我的LINQtoSQL查询,它工作得很好,但是当我转换并返回数据时,我得到了转换错误C# 有人能帮我在linq查询下施展吗?,c#,linq,entity-framework,linq-to-sql,C#,Linq,Entity Framework,Linq To Sql,这是我的LINQtoSQL查询,它工作得很好,但是当我转换并返回数据时,我得到了转换错误 var productImages = from prod in context.seller_productinventory.AsEnumerable() join prodImage in context.seller_productimages on prod.prdid equals prodImage.prdid
var productImages = from prod in context.seller_productinventory.AsEnumerable()
join prodImage in context.seller_productimages on prod.prdid equals prodImage.prdid
join category in context.mstr_scategory on prod.mcid equals category.CategoryID
join subcategory in context.mstr_scategory on prod.scid equals subcategory.CategoryID
select new
{
ProductId = prod.prdid,
Category = category.CategoryName,
Subcategory = subcategory.CategoryName,
Image1 = prodImage.image1Path,
Image2 = prodImage.image2Path,
Image3 = prodImage.image3Path,
Image4 = prodImage.image4Path,
ProductStatusCd = (Convert.ToInt32(prod.isAdminApproved) != 1) ? "Pending Approval" : "Approved"
};
我在下面的代码中得到错误
return (IEnumerable<ProductImageModel>) productImages.ToList();
您正在使用
select new
选择一个匿名对象,稍后您试图将一组匿名对象强制转换为IEnumerable
,这将失败
你有两个选择来解决这个问题
如果类ProductImageModel
不是通过实体框架生成的,则可以在select语句中使用该类,如:
select new ProductImageModel
{
//.... fields
}
或者,另一个选项是创建一个临时模板类,并将字段投影到该类对象
请记住,如果框架生成了ProductImageModel
,则不能在使用选择的列投影中使用该框架
从您的代码来看,您的类ProductImageModel
实际上代表了数据库中的一个表。您将需要另一个类(DTO),该类包含select
子句中指定的字段
public class ProductImageModelDTO
{
//your fields
}
然后在LINQ查询中:
select new ProductImageModelDTO
{
ProductId = prod.prdid,
//rest of the fields.
在这种情况下,您的方法返回类型应为:
IEnumerable<ProductImageModelDTO>
IEnumerable
当您选择新建{…}
时,您正在创建匿名对象。本质上,您最终得到的是IQueryable
,这与IEnumerable
是相反的(即编译器不能从一个强制转换到另一个)。最简单的解决方案是选择actualProductImageModel
s,如果这是您要使用的:
select new ProductImageModel
{
...
}
然后,不需要强制转换。那么错误是什么呢?这是因为您选择的是一种
匿名
类型。我完全理解这个问题,但感觉不好的做法是您最终得到了一个实体框架/linq2sql对象/类样的产品。在这种情况下,您不能真正使用它,因此您必须创建另一个say产品类,该类不绑定到您可以实际映射到的实体框架或linq2sql。这对其他人来说很正常吗?因此,您将得到两个类,一个特定于db模型,另一个作为抽象数据类型,您可以使db模型对象成为抽象数据类型+无论如何,非常感谢你@chrispratt@JonH:不是你不能使用实体;这很少有意义。创建另一个类并将实体数据映射到该类,可以让您自由并能够为特定目的自定义该类。典型的用例是视图模型,视图模型是为处理特定视图或一组视图而定制的类。有了这些视图模型,您就可以拥有强类型视图特定的数据,这些数据不适合放在您的数据库实体上,例如选择列表。非常好地解释了+1。@SanjuRao,欢迎您。我相信如果它运行得如此之快,那么它一定是选项1,因此您的类ProductImageModel
不是通过框架生成的。是的@Habib您完全正确,ProductImageModel类是由我编写的,而不是从.edmx类生成的。
select new ProductImageModel
{
...
}