Linq-To-Entities使用方法选择新对象 [英] Linq-To-Entities using method to select new object
问题描述
我尝试在我的应用程序中多次使用相同的选择查询.例如,我有以下选择语句:
I try to use the same select query multiple times in my application. For example I have this select statement:
_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,
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
}
})
});
如您所见,我在两个linq select语句中都使用了完全相同的代码(对于SingleItemDTO).有没有办法分离我的第一个select语句的代码(不获取NotSupportedException)并再次使用它?我的第二个查询应如下所示:
As you can see I use exactly the same code (for the SingleItemDTO) in both linq select statements. Is there a way to separate the code of my first select statement (without getting the NotSupportedException) and reuse it again? My second query should look like this:
_db.tbl_itembundle
.Where(x => x.type == 2)
.Select(y => new ItemBundleDTO
{
name = y.name,
namekey = y.namekey.
contents = y.tbl_itembundlecontents.ToDTO()
});
推荐答案
有可能,但是有点不寻常.
It's possible, but in a bit unusual way.
创建一个帮助方法,并像这样移动您的第一个查询的 selector 部分
Create a helper method and move the selector part of your first query like this
static Expression<Func<[tbl_itembundlecontents entity type], SingleItemDTO>> ToSingleItemDTO()
{
return 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
}
};
}
现在第一个查询可以是这样
Now the first query can be like this
_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()
,这是使其工作的必要部分.
Note the AsQueryable()
after the navigation property, this is the esential part to make it work.
这篇关于Linq-To-Entities使用方法选择新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!