【发布时间】:2016-09-20 03:53:51
【问题描述】:
我喜欢使用扩展方法将我的实体模型投影到我的视图模型中。这意味着我不会过度/不足地获取我的模型,它使代码变得美观且可读。有时投影可能包含嵌套模型是有道理的,我想在这些子投影上重用。
我希望能够执行以下操作:
ctx.People.FiltersAndThings().ToViewModels();//the project my DB Models into view models
实际投影的扩展方法
public static IQueryable<PersonModel> ToViewModels(this IQueryable<Person> entities)
{
return entities.Select(x => new PersonModel {
Me = x.Me.ToViewModel(), //this method cannot be translated into a store expression
Friends = x.Friends.AsQueryable().ToViewModels() //works fine with some magic (tm)
});
}
public static IQueryable<ProfileModel> ToViewModels(this IQueryable<Profile> entities)
{
return entities.Select(x => new ProfileModel { Name = x.Name });
}
public static ProfileModel ToViewModel(this Profile entity)
{
return new ProfileModel { Name = entity.Name };
}
当使用 Queryable(例如 Friends = x.Friends.AsQueryable().ToViewModels())时,我们可以使用一些魔法将其展平为表达式(参见 https://stackoverflow.com/a/10726256/1070291,@LordTerabyte 的回答)但是当我们使用新子句进行赋值时(例如 @987654329 @) 它不是一个表达式,所以如果我们将它捆绑在一个扩展方法下(例如Me = x.Me.ToViewModel()),我们就不能将它展平为一个表达式。
在 EF 的场景下如何分配给新对象?
有没有办法通过扩展方法转换为新对象?
完整的演示代码在这里:https://github.com/lukemcgregor/ExtensionMethodProjection
编辑:
我现在有一篇博文 (Composable Repositories - Nesting Extensions) 和 nuget package 来帮助在 linq 中嵌套扩展方法
【问题讨论】:
-
它是否适用于您当前的代码?
-
Me = x.Me.ToViewModel()不起作用,如果您想要一个其余工作的演示应用程序,我可以发布到 GH -
其实看看你的
Person模型和PersonModel会有所帮助,不是完整代码,而是相关部分。 -
有点牵强,但这行得通吗:
Me = x.Friends.AsQueryable().ToViewModels().Where(n => n.Name = x.Me.Name).Single() -
控制台应用程序中的完整工作代码:github.com/lukemcgregor/ExtensionMethodProjection
标签: c# entity-framework expression-trees