yDe*_*per 4 c# linq asp.net-mvc linq-to-entities entity-framework
我尝试在我的应用程序中多次使用相同的选择查询.例如,我有这个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
}
});
Run Code Online (Sandbox Code Playgroud)
但我也有这个:
_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
}
})
});
Run Code Online (Sandbox Code Playgroud)
如您所见,我在两个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()
});
Run Code Online (Sandbox Code Playgroud)
这是可能的,但有点不寻常.
创建一个帮助方法并像这样移动第一个查询的选择器部分
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
}
};
}
Run Code Online (Sandbox Code Playgroud)
现在第一个查询可以是这样的
_db.tbl_itembundlecontents.Select(ToSingleItemDTO());
Run Code Online (Sandbox Code Playgroud)
而第二个像这样
_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())
});
Run Code Online (Sandbox Code Playgroud)
请注意,AsQueryable()在导航属性之后,这是使其工作的必要部分.
小智 2
像这样的东西?
public static class HelperExtension
{
public static IEnumerable<SingleItemDTO> ToDto(this IEnumerable<Tbl_itembundlecontents> items)
{
return items.Select(z => z.ToDto());
}
public static SingleItemDTO ToDto(this Tbl_itembundlecontents z)
{
return 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
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8089 次 |
| 最近记录: |