仅从已实现的接口中检索字段

问题描述 投票:0回答:2

我有一个类,其中添加了 IAuxiliary 和 ICachable 中的字段。我想返回对象列表,但只想共享 IAuxiliary 中的字段。

    public interface IAuxiliary
{
    int Id { get; }
    string? Label { get; set; }
}

public interface ICachable : IAuxiliary
{
    int SortOrder { get; set; }
    bool IsActive { get; set; }
    bool IsDefault { get; set; }
}

public class ContractType : ICachable
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ContractTypeId { get; set; }
    [NotMapped]
    public int Id { get { return ContractTypeId; } }
    [StringLength(50, MinimumLength = 3)]
    public string? Label { get; set; }
    public int SortOrder { get; set; }
    public bool IsActive { get; set; }
    public bool IsDefault { get; set; }
}

下面的语句给了我contractType的所有属性,我只需要Id和Label。

        var aux = from c in _appDbContext.ContractTypes
                  where c.IsActive
                  orderby c.SortOrder
                  select c as IAuxiliary;
linq interface dbset
2个回答
0
投票

为什么不使用Enumerable.Cast

IEnumerable<ContractType> contracts = ...
IEnumerable<IAuxiliary> auxiliaries = contracts.Cast<IAuxiliary>();

这对于大多数应用来说已经足够了。

当然,不能保证人们不会将物品强制转换回 ContractTypes。 如果您绝对想阻止这些人,例如出于安全原因,您不希望人们能够检查 ContractTypes 的其他属性,则必须创建仅包含 IAuxiliary 属性的新对象。但请注意,这会消耗更多的处理能力。

在下面的示例中我使用扩展方法。如果您不熟悉扩展方法,请考虑阅读扩展方法揭秘

public static IEnumerable<IAuxiliary> ToAuxiliary(this IEnumerable<ContractType> contract)
{
    // define local class that implements IAuxiliary
    class Auxiliary : IAuxiliary
    {
         public int Id => this.contractType.Id;
         public string? Label
         {
             get => this.contractType.Label;
             set => this.contractType.Label = value;
         }
    }

    // the code to create the Auxiliaries:
    if (contracts == null) throw ArgumentNullException(...);

    return contracts

        // only if you expect null contractTypes:
        .Where(contractType => contractType != null)

        // create Auxiliaries
        .Select(contractType => new Auxiliary
        {
            Id = contractType.Id,
            Label = contractType.Label,
        });
}

用途:

IEnumerable<ContractType> contracts = ...
IEnumerable<IAuxiliary> auxiliaries = contracts.ToAuxiliaries();

0
投票

我在下面使用将所有辅助类型视为 OCachable

_appDbContext.Set<ContractType>().OfType<ICachable>()

然后我只是使用 automapper 来仅检索 id 和标签。一旦实施完成,将考虑仅选择 id 和标签。

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