如何通过LINQ将同一个类的对象属性合并在一起

问题描述 投票:-1回答:1

假设我有一个类,我想选择它的多个对象,但最后创建一个统一的对象。这是因为要求组合对象的集合属性。

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Microsoft.EntityFrameworkCore.Internal;
using Nozomi.Base.Core;

namespace Nozomi.Data.Models.Currency
{
    public class Currency : BaseEntityModel
    {
        public Currency(ICollection<Currency> currencies)
        {
            if (currencies.Any())
            {
                var firstCurr = currencies.FirstOrDefault();

                if (firstCurr != null)
                {
                    // Doesn't matter...
                    Id = firstCurr.Id;
                    CurrencyTypeId = firstCurr.Id;
                    CurrencyType = firstCurr.CurrencyType;
                    Abbrv = firstCurr.Abbrv;
                    Name = firstCurr.Name;
                    CurrencySourceId = firstCurr.CurrencySourceId;
                    CurrencySource = firstCurr.CurrencySource;
                    WalletTypeId = firstCurr.WalletTypeId;
                    PartialCurrencyPairs = currencies
                        .SelectMany(c => c.PartialCurrencyPairs)
                        .DefaultIfEmpty()
                        .ToList();
                }
            }
        }

        [Key]
        public long Id { get; set; }

        public long CurrencyTypeId { get; set; }
        public CurrencyType CurrencyType { get; set; }

        public string Abbrv { get; set; } // USD? MYR? IND?

        public string Name { get; set; }

        public long CurrencySourceId { get; set; }
        public Source CurrencySource { get; set; }

        // This will have a number if it is a crypto pair to peg to proper entities
        public long WalletTypeId { get; set; } = 0;

        public ICollection<PartialCurrencyPair> PartialCurrencyPairs { get; set; }

        public bool IsValid()
        {
            return !String.IsNullOrEmpty(Abbrv) && !String.IsNullOrEmpty(Name) && CurrencyTypeId > 0 && CurrencySourceId > 0;
        }
    }
}

这是PartialCurrencyPair的内容:

namespace Nozomi.Data.Models.Currency
{
    /// <summary>
    /// Partial currency pair.
    /// </summary>
    public class PartialCurrencyPair
    {
        public long CurrencyId { get; set; }

        public long CurrencyPairId { get; set; }

        public bool IsMain { get; set; } = false;

        public CurrencyPair CurrencyPair { get; set; }
        public Currency Currency { get; set; }
    }
}

所以基本上,如果你想赚取欧元兑美元,你将不得不采取两种货币形成一对。 CurrencyPair由两个PartialCurrencyPairs组成。我们可以拥有多少欧元或许多美元的原因是它们来自不同的来源。

这是CurrencyPair的内容:

public class CurrencyPair : BaseEntityModel
    {
        [Key]
        public long Id { get; set; }

        public CurrencyPairType CurrencyPairType { get; set; }

        /// <summary>
        /// Which CPC to rely on by default?
        /// </summary>
        public string DefaultComponent { get; set; }

        public long CurrencySourceId { get; set; }
        public Source CurrencySource { get; set; }

        // =========== RELATIONS ============ //
        public ICollection<CurrencyPairRequest> CurrencyPairRequests { get; set; }
        public ICollection<WebsocketRequest> WebsocketRequests { get; set; }
        public ICollection<PartialCurrencyPair> PartialCurrencyPairs { get; set; }

        public bool IsValid()
        {
            var firstPair = PartialCurrencyPairs.First();
            var lastPair = PartialCurrencyPairs.Last();

            return (CurrencyPairType > 0) && (!string.IsNullOrEmpty(APIUrl)) 
                                          && (!string.IsNullOrEmpty(DefaultComponent))
                                          && (CurrencySourceId > 0)
                                          && (PartialCurrencyPairs.Count == 2)
                                          && (firstPair.CurrencyId != lastPair.CurrencyId)
                                          && (!firstPair.IsMain == lastPair.IsMain);
        }
    }

我有一个IQueryable可以组合成一种货币。

带注释的代码(评论基本上告诉你我想要实现的目标。

var query = _unitOfWork.GetRepository<Currency>()
                .GetQueryable()
                // Do not track the query
                .AsNoTracking()
                // Obtain the currency where the abbreviation equals up
                .Where(c => c.Abbrv.Equals(abbreviation, StringComparison.InvariantCultureIgnoreCase)
                            && c.DeletedAt == null && c.IsEnabled)
                // Something here that will join the PartialCurrencyPair collection together and create one single Currency object.
                .SingleOrDefault();

我怎么来的?非常感谢你前进!这是我到目前为止所取得的进展,但它很有效,但我很漂亮LINQ有一种漂亮的方法可以让它变得更好和优化:

var combinedCurrency = new Currency(_unitOfWork.GetRepository<Currency>()
                .GetQueryable()
                // Do not track the query
                .AsNoTracking()
                // Obtain the currency where the abbreviation equals up
                .Where(c => c.Abbrv.Equals(abbreviation, StringComparison.InvariantCultureIgnoreCase)
                            && c.DeletedAt == null && c.IsEnabled)
                .Include(c => c.PartialCurrencyPairs)
                .ThenInclude(pcp => pcp.CurrencyPair)
                .ThenInclude(cp => cp.CurrencyPairRequests)
                .ThenInclude(cpr => cpr.RequestComponents)
                .ThenInclude(rc => rc.RequestComponentDatum)
                .ThenInclude(rcd => rcd.RcdHistoricItems)
                .ToList());


return new DetailedCurrencyResponse
                {
                    Name = combinedCurrency.Name,
                    Abbreviation = combinedCurrency.Abbrv,
                    LastUpdated = combinedCurrency.PartialCurrencyPairs
                        .Select(pcp => pcp.CurrencyPair)
                        .SelectMany(cp => cp.CurrencyPairRequests)
                        .SelectMany(cpr => cpr.RequestComponents)
                        .OrderByDescending(rc => rc.ModifiedAt)
                        .FirstOrDefault()?
                        .ModifiedAt ?? DateTime.MinValue,
                    WeeklyAvgPrice = combinedCurrency.PartialCurrencyPairs
                        .Select(pcp => pcp.CurrencyPair)
                        .Where(cp => cp.CurrencyPairRequests
                            .Any(cpr => cpr.DeletedAt == null && cpr.IsEnabled))
                        .SelectMany(cp => cp.CurrencyPairRequests)
                        .Where(cpr => cpr.RequestComponents
                            .Any(rc => rc.DeletedAt == null && rc.IsEnabled))
                        .SelectMany(cpr => cpr.RequestComponents
                            .Where(rc =>
                                rc.ComponentType.Equals(ComponentType.Ask) ||
                                rc.ComponentType.Equals(ComponentType.Bid)))
                        .Select(rc => rc.RequestComponentDatum)
                        .SelectMany(rcd => rcd.RcdHistoricItems
                            .Where(rcdhi => rcdhi.CreatedAt >
                                            DateTime.UtcNow.Subtract(TimeSpan.FromDays(7))))
                        .Select(rcdhi => decimal.Parse(rcdhi.Value))
                        .DefaultIfEmpty()
                        .Average(),
                    DailyVolume = combinedCurrency.PartialCurrencyPairs
                        .Select(pcp => pcp.CurrencyPair)
                        .Where(cp => cp.CurrencyPairRequests
                            .Any(cpr => cpr.DeletedAt == null && cpr.IsEnabled))
                        .SelectMany(cp => cp.CurrencyPairRequests)
                        .Where(cpr => cpr.RequestComponents
                            .Any(rc => rc.DeletedAt == null && rc.IsEnabled))
                        .SelectMany(cpr => cpr.RequestComponents
                            .Where(rc => rc.ComponentType.Equals(ComponentType.VOLUME)
                                         && rc.DeletedAt == null && rc.IsEnabled))
                        .Select(rc => rc.RequestComponentDatum)
                        .SelectMany(rcd => rcd.RcdHistoricItems
                            .Where(rcdhi => rcdhi.CreatedAt >
                                            DateTime.UtcNow.Subtract(TimeSpan.FromHours(24))))
                        .Select(rcdhi => decimal.Parse(rcdhi.Value))
                        .DefaultIfEmpty()
                        .Sum(),
                    Historical = combinedCurrency.PartialCurrencyPairs
                        .Select(pcp => pcp.CurrencyPair)
                        .SelectMany(cp => cp.CurrencyPairRequests)
                        .SelectMany(cpr => cpr.RequestComponents)
                        .Where(rc => componentTypes != null 
                                     && componentTypes.Any()
                                     && componentTypes.Contains(rc.ComponentType)
                                     && rc.RequestComponentDatum != null
                                     && rc.RequestComponentDatum.IsEnabled 
                                     && rc.RequestComponentDatum.DeletedAt == null
                                     && rc.RequestComponentDatum.RcdHistoricItems
                                         .Any(rcdhi => rcdhi.DeletedAt == null &&
                                                       rcdhi.IsEnabled))
                        .ToDictionary(rc => rc.ComponentType,
                            rc => rc.RequestComponentDatum
                                .RcdHistoricItems
                                .Select(rcdhi => new ComponentHistoricalDatum
                                {
                                    CreatedAt = rcdhi.CreatedAt,
                                    Value = rcdhi.Value
                                })
                                .ToList())
                };

这是我想要在该单个对象上的最终结果:DetailedCurrencyResponse对象。

public class DistinctiveCurrencyResponse
    {
        public string Name { get; set; }

        public string Abbreviation { get; set; }

        public DateTime LastUpdated { get; set; }

        public decimal WeeklyAvgPrice { get; set; }

        public decimal DailyVolume { get; set; }
    }

历史数据基本上是kvp,其中Key(ComponentType)是枚举。

public class DetailedCurrencyResponse : DistinctiveCurrencyResponse
    {
        public Dictionary<ComponentType, List<ComponentHistoricalDatum>> Historical { get; set; }
    }

public class ComponentHistoricalDatum
    {
        public DateTime CreatedAt { get; set; }

        public string Value { get; set; }
    }
c# entity-framework linq unit-of-work
1个回答
0
投票

您概述的查询将尝试返回单个Currency对象,但鉴于您正在查找具有给定缩写的任何对象,如果多个货币对象共享缩写,则SingleOrDefault可能由于多次返回而出错。

听起来你想要定义一个结构来代表货币对。该结构不是货币实体,而是不同的数据表示。这些通常称为ViewModels或DTO。一旦定义了要返回的内容,就可以使用.Select()从Currency和适用的缩写中填充它。

例如,如果我创建一个CurrencySummaryDto,它将包含货币ID,缩写和包含所有适用对的字符串:

public class CurrencySummaryDto
{
    public long CurrencyId { get; set; }
    public string Abbreviation { get; set; }
    public string Pairs { get; set;} 
}

...然后查询......

var currencySummary = _unitOfWork.GetRepository<Currency>()
    .GetQueryable()
    .AsNoTracking()
    .Where(c => c.Abbrv.Equals(abbreviation, StringComparison.InvariantCultureIgnoreCase)
        && c.DeletedAt == null && c.IsEnabled)
    .Select( c => new {
        c.Id,
        c.Abbrv,
        Pairs = c.PartialCurrencyPairs.Select(pc => pc.PairName).ToList() // Get names of pairs, or select another annonymous type for multiple properties you care about...
    }).ToList() // Alternatively, when intending for returning lots of data use Skip/Take for paginating or limiting resulting data.    
    .Select( c => new CurrencySummaryDto
    {
        CurrencyId = c.Id,
        Abbreviation = c.Abbrv,
        Pairs = string.Join(", ", c.Pairs)
    }).SingleOrDefault();

如果你想做一些事情,比如将来自货币对的数据组合成类似字符串的东西。如果您乐意将它们作为简化数据的集合保留,则不需要额外的匿名类型和.ToList(),只需直接选择Dto结构即可。此示例将数据组合到一个字符串中,其中EF表达式中不支持string.Join(),因此我们必须将数据输出到对象中以交给Linq2Object进行最终映射。

编辑:好的,您的要求/示例只是使对结构变得更加复杂,但您应该能够将其用于查询而不是通过将这些值的选择移动到选择整个实体图主要问题......但......

鉴于数据关系的复杂性,我建议使用的方法,因为这将被假定为只读结果,将在数据库中构造一个视图以展平这些平均值和总数,然后将简化实体绑定到此查看而不是尝试使用EF Linq进行管理。我相信它可以用linq来完成,但是看起来会非常繁琐,并且基于视图的摘要实体会更加清晰,同时保持在数据库中执行此逻辑的执行。

© www.soinside.com 2019 - 2024. All rights reserved.