如何在Expression< Func<< ...>&gt ;? [英] How to reuse code inside a Expression<Func< ... >>?

查看:94
本文介绍了如何在Expression< Func<< ...>&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是表达式的新手,我正在和它们玩耍.

I'm new to expressions and I'm playing around with them.

具有在Linq to实体context.Products.Select(AsProductDto)中使用的表达式:

Having this expression for use in Linq to Entities context.Products.Select(AsProductDto):

internal static readonly Expression<Func<Product, ProductDto>> 
    AsProductDto = product => new ProductDto 
    {
       // repeated code 
       Name = product.name 
       // ...
    };

我也想拥有这个构造函数:

I also want to have this constructor :

public class ProductDto {
    public ProductDto() { }
    public ProductDto(Product product) 
    {
       // repeated code 
       Name = product.name 
       // ...
    }
}

由于Linq to Entities中无参数构造函数的要求,我无法使用

because of parameterless constructors requirement in Linq to Entities I cannot use

internal static readonly Expression<Func<Product, ProductDto>> 
        AsProductDto = product => new ProductDto(product)

无论如何,我是否可以重用(也就是不重复)标记为重复的代码部分?

Is there anyway I can reuse (aka not repeat) the portion of the code marked as repeated ?

推荐答案

出于删除某些重复项的目的,您可能会在ProductDto类中为Product引入二传手(setter)

for the purpose of removing some duplicate you may perhaps introduce a setter for the Product in ProductDto class

这种方法可以帮助您减少大部分重复的行,

this approach may help you reduce most of your duplicated lines,

仅当您重复了几行时,这才是有益的.复制产品的几个属性.

this will be beneficial only when you have a couple of lines duplicated eg. copying a couple of properties of the product.

示例

    internal static readonly Expression<Func<Product, ProductDto>>
        AsProductDto = product => new ProductDto
        {
            // single line call to setter
            Product = product
        };

    public class ProductDto
    {
        public ProductDto() { }
        public ProductDto(Product product)
        {
            // single line call to setter
            Product = product;
        }
        public ProductDto Product
        {
            set
            {
                // no more repeated code 
                Name = value.name;
                // ...
            }
        }
    }

这篇关于如何在Expression&lt; Func&lt;&lt; ...&gt;&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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