当域模型具有抽象属性时,DTO的外观如何?

时间:2018-10-07 21:08:57

标签: c#

我正在编写一个RESTful API,其中实体保留在Azure存储表服务中。

我的一个实体是Tenant实体,它看起来像这样:

public class TenantEntity : BaseEntity
{
    public string Name
    {
        get => PartitionKey;
        set
        {
            PartitionKey = value;
            RowKey = value;
        }
    }

    [JsonIgnore]
    public string DefaultActionSerialized
    {
        get => JsonConvert.SerializeObject(DefaultAction);
        set => DefaultAction = JsonConvert.DeserializeObject<ScheduledAction>(value);
    }

    [IgnoreProperty]
    public ScheduledAction DefaultAction { get; set; }
}

[JsonConverter(typeof(ScheduledActionJsonConverter))]
public abstract class ScheduledAction
{
    public abstract ScheduledActionType ActionType { get; }

    public override string ToString()
    {
        return JsonConvert.SerializeObject(this);
    }
}

[JsonConverter(typeof(StringEnumConverter))]
public enum ScheduledActionType
{
    StorageQueueMessage,
    Webhook
}

请注意DefaultAction类型的ScheduledAction属性。 我最初的想法是将支持多个 ScheduledActions ,例如将消息放入队列中或调用Webhook等。

但是,我不确定Tenant实体的DTO会是什么样子。 我应该为抽象的ScheduledAction类复制并创建一个DTO,然后对其每个继承者进行相同的操作吗?

如果您将其建模为其他模型,那么我也很高兴听到有关此消息的信息,但是为了体验DTO,请回答这个问题也很高兴:)

现在,TenantDto类如下所示:

public class TenantDto
{
    [Required]
    [FromRoute(Name = "tenant")]
    [JsonProperty("TenantName")]
    [RegularExpression("^[a-z][a-z0-9]+$")]
    [StringLength(maximumLength: 24, MinimumLength = 3)]
    public string TenantName { get; set; }

    [Required]
    [JsonProperty("ScheduledAction")]
    public ScheduledAction ScheduledAction { get; set; }

    public static implicit operator TenantEntity(TenantDto tenantDto)
    {
        return new TenantEntity
        {
            Name = tenantDto.TenantName,
            DefaultAction = tenantDto.ScheduledAction,
        };
    }
}

它引用了域模型ScheduledAction,我知道这是一种不好的做法,但是找不到对我来说更有意义的解决方案。

感谢您的帮助!

0 个答案:

没有答案