如何定义表达式选择嵌套在实体框架一到一对一的关系 [英] How to define expression selection nested one-to-one relationship in Entity Framework

查看:145
本文介绍了如何定义表达式选择嵌套在实体框架一到一对一的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图运行一个LINQ到实体包含此表达式进入实体框架。

I am trying to run a Linq-to-Entity that contains this Expression into Entity Framework.

不工作:

//2 seperated expressions, 1st expression calling the 2nd expression
public Expression<Func<User, UserDto>> UserToDtoExpr() {
    var expr = AddressToDtoExpr();
    return x => new UserDto() {
        Id = x.Id,
        Name = x.Name,
        Address = expr.Compile()(x.Address)
    };  
}
public Expression<Func<Address, AddressDto>> AddressToDtoExpr() {
    return x => New AddressDto() {
        Id = x.Id,
        City = x.City,
        Country= x.Country
    };
}



例外的LINQ表达式节点类型调用不LINQ支持实体。

现在,我如果硬编码和其嵌套在一个表达式,放入LINQ到实体,然后它的工作原理:

Now, I if hardcode and nest it into one Expression and put it into Linq-to-Entity then it works:

//hardcode combined together into 1 expression with nested object
public static Expression<Func<User, UserDto>> UserToDtoExpr() {
    return x => new UserDto() {
        Id = x.Id,
        Name = x.Name,
        Address = New AddressDto() {
            Id = x.Address.Id,
            City= x.Address.City,
            Country = x.Address.Country
        }
    };  
}



但我不想硬编码像第二种方法,因为我要modularise和重用这些表达式功能。如何解决了第一个方法,使工作?谢谢你。

But I don't want to hardcode it like the 2nd way, because I want to modularise and reuse these Expression functions. How do I fix up the 1st way to make it work? Thanks.

推荐答案

您需要使用的 LinqKit AsExpandable()来实现这一目标。

You need to use LinqKit's AsExpandable() to achieve this.

第一,改变你的表达式中使用LinqKit的的invoke()(扩展方法)如下:

First, change your expression to use LinqKit's Invoke() (extension method) as follows:

Address = expr.Invoke(x.Address) // instead of expr.Compile()(x.Address)

然后使用 AsExpandable() DbSet< T>

var results = context.Users.AsExpandable().Select(UserToDtoExpr());



阅读的这个来了解与嵌套表达式的问题。

Read this to understand the problem with nested expressions.

这篇关于如何定义表达式选择嵌套在实体框架一到一对一的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆