【问题标题】:Dynamically construct select field in Linq to Entities在 Linq to Entities 中动态构造选择字段
【发布时间】:2013-07-02 23:54:36
【问题描述】:

在我的简单数据库第一个实体框架场景中,我的客户分配了价目表编号。另一方面,有一个产品表,其中有 7 个价格列对应于价目表,例如PR_1、PR_2、PR_3等

我想对一些属性进行投影。问题是属性/字段之一取决于客户的价目表编号,因此需要动态构建。因此,如果价目表编号为 2,则要使用的属性为 PR_2,依此类推。

public IList<Product> GetSalesList(int customerId)
{
    Customer customer = this.customerService.Get(customerId);

    var products = this.productRepository.GetAll().OrderBy(p => p.ProductCode)
            .Select(p => new Product
            {
                Id = p.Id,
                ProductCode = p.ProductCode,
                Description = p.Description,
                PricingTypeCode = p.PricingTypeCode,
                Quantity = 0,
                SalesPrice = <<PR_ + customer.PricelistNumber.ToString()>> 
             }).ToList();

    return products;
}

我已经阅读了有关 LINQ 的信息,但我不想使用它,因为我认为这只是一个例外。

谁能指出我正确的方向或有人对此有解决方案吗?

【问题讨论】:

    标签: c# entity-framework select linq-to-entities ef-database-first


    【解决方案1】:

    我会将所有价格存储在Product 中,然后使SalesPrice 成为根据客户的价目表编号计算销售价格的方法。

    类似:

    public decimal SalesPrice(Customer customer)
    {
        return prices[customer.PriceListNumber - 1];
    }
    

    【讨论】:

    • 谢谢,我认为这是一个不错的选择,但在我的场景中,Product 是一个 DTO。所以这个方法将进入服务。我仍然更喜欢选择字段的动态构造。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 2015-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    相关资源
    最近更新 更多