2014-07-10 84 views
0

在Linq to SQL asp.net中,我想从数据库中提取特定图像并显示在aspx页面上。我在代码中声明返回类型为“var”。所以在获取图像之后,它将图像分配给var类型。如何将类型'system.linq.iqueryable <byte[]>'转换为'byte []'

下面是代码:

var db = from c in context.Images 
         where c.imageId == iID 
         select c.imageData; 
return new MemoryStream((byte[])db); ---->> this line of code gives error 

它给出了这样的编译错误:无法转换类型 'system.linq.iqueryable' 到 '字节[]'。

如何将'system.linq.iqueryable类型转换为byte []?

+0

你应该使用LINQ中的SingleOrDefault选择,这样你就可以得到的只是一个单一的对象,不是IQueryable。同样在SingleOrDefault <>中,您可以指定类型以避免铸造 – Carlos487

回答

3

您的问题是,您选择的是byte[]的集合,而不是单个的byte[]

取决于你想为你的应用程序的行为,你可以使用SingleSingleOrDefaultFirst,或FirstOrDeault

var image = context.Images.FirstOrDefault(i => i.imageId == ID); 
if(image == null) 
{ 
    // Handle the case where no image was found. 
    // 
    // First or Single would throw Exceptions in this case 
    // if that's what you want. 
} 
else 
{ 
    return new MemoryStream(image.imageData); 
} 
+0

错误消失,它可以工作。谢谢! – perlynsparks

+0

对不起贾斯汀,你能帮我解答一下吗? http://stackoverflow.com/questions/24699751/how-to-return-the-query-result-as-a-specific-object-type-in​​-linq – perlynsparks

相关问题