c# - 加入表时丢弃“匿名”异常
问题描述
我很困惑,例如如何在不出现“匿名”异常的情况下加入两个表;例如以下代码部分:
var result = (from prod in context.ProductsTbls
join imag in context.ProductImagesTbls
on prod.Id equals imag.ProductId
where prod.UserId == 4 && imag.IsDefaultImage == true
select new
{
Id = prod.Id,
ProductName = prod.ProductName,
ProductDescription = prod.ProductDescription,
ProductCategory = prod.ProductCategory,
ProductPricePerDay = prod.ProductPricePerDay,
ProductPricePerWeek = prod.ProductPricePerWeek,
ProductPricePerMonth = prod.ProductPricePerMonth,
CreationDate = prod.CreationDate,
ModificationDate = prod.ModificationDate,
Image = imag.Image
}).ToList();
IEnumerable<ProductsTbl> data =
(IEnumerable<ProductsTbl>)result.ToList(); // Exception appears here
DataTable table = new DataTable();
using (var reader = ObjectReader.Create(data, "Id", "Image"))
{
table.Load(reader);
}
执行上述代码后,我得到这个异常:
System.InvalidCastException: 'Unable to cast object of type
'System.Collections.Generic.List`1[<>f__AnonymousType1`10[System.Int32,System.Str
ing,System.String,System.String,System.Nullable`1[System.Int32],System.Nullable`1
[System.Int32],System.Nullable`1[System.Int32],System.Nullable`1[System.DateTime]
,System.Nullable`1[System.DateTime],System.Byte[]]]' to type
'System.Collections.Generic.IEnumerable`1[ClassLibrary1.ProductsTbl]'.'
解决方案
通常,当您需要 LINQ 查询的结果是IEnumerable
某个类型的一个或集合时,您需要在select
.
所以,而不是select new {
...}
你会使用:
select new ProductsTbl {
// put field values here
}
推荐阅读
- arrays - PointCloud 组件渲染问题 fetch() 自定义数据 [react-three-fiber]
- angular - 角度 8 错误:模块“AppModule”导入的意外值“HttpClient”。请添加@NgModule 注释
- c - 如何在C中只接受整数值
- testing - 我在赛普拉斯测试中将 get() 中的超时参数传递给 should() 时遇到问题
- python - 数据框中的 Python 积分函数计算错误
- go - 错误:不能在类型的结构文字中使用提升的字段
- .net-core - AuthenticationException WebAPI / ASP MVC dotnet Core
- docker - docker-swarm + nginx 负载平衡:我需要在 .conf 中设置上游吗?
- c# - 通过脚本在运行时实例化按钮具有正确声明的 onClick 函数
- javascript - 尝试使用反应挂钩从 API 显示数据时出现类型错误