c# – 使用方法选择新对象的Linq-To-Entities
发布时间:2020-12-15 23:28:47 所属栏目:百科 来源:网络整理
导读:我尝试在我的应用程序中多次使用相同的选择查询. 例如,我有这个select语句: _db.tbl_itembundlecontents .Select(z = new SingleItemDTO { amount = z.amount,id = z.id,position = z.position,contentType = new BasicMaterialDTO { id = z.tbl_items.id,i
我尝试在我的应用程序中多次使用相同的选择查询.
例如,我有这个select语句: _db.tbl_itembundlecontents .Select(z => new SingleItemDTO { amount = z.amount,id = z.id,position = z.position,contentType = new BasicMaterialDTO { id = z.tbl_items.id,img = z.tbl_items.tbl_material.img,name = z.tbl_items.tbl_material.name,namekey = z.tbl_items.tbl_material.namekey,info = z.tbl_items.tbl_material.info,weight = z.tbl_items.tbl_material.weight } }); 但我也有这个: _db.tbl_itembundle .Where(x => x.type == 2) .Select(y => new ItemBundleDTO { name = y.name,namekey = y.namekey. contents = y.tbl_itembundlecontents .Select(z => new SingleItemDTO { amount = z.amount,weight = z.tbl_items.tbl_material.weight } }) }); 如您所见,我在两个linq select语句中使用完全相同的代码(对于SingleItemDTO).有没有办法分离我的第一个select语句的代码(没有得到NotSupportedException)并重新使用它?我的第二个查询应如下所示: _db.tbl_itembundle .Where(x => x.type == 2) .Select(y => new ItemBundleDTO { name = y.name,namekey = y.namekey. contents = y.tbl_itembundlecontents.ToDTO() }); 解决方法
这是可能的,但有点不寻常.
创建一个帮助方法并像这样移动第一个查询的选择器部分 static Expression<Func<[tbl_itembundlecontents entity type],SingleItemDTO>> ToSingleItemDTO() { return z => new SingleItemDTO { amount = z.amount,contentType = new BasicMaterialDTO { id = z.tbl_items.id,weight = z.tbl_items.tbl_material.weight } }; } 现在第一个查询可以是这样的 _db.tbl_itembundlecontents.Select(ToSingleItemDTO()); 而第二个像这样 _db.tbl_itembundle .Where(x => x.type == 2) .Select(y => new ItemBundleDTO { name = y.name,namekey = y.namekey. contents = y.tbl_itembundlecontents.AsQueryable().Select(ToSingleItemDTO()) }); 注意导航属性之后的AsQueryable(),这是使其工作的必要部分. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |