【问题标题】:ASP.NET Core Web API - The name 'jsonString' does not exist in the current contextASP.NET Core Web API - 当前上下文中不存在名称“jsonString”
【发布时间】:2022-01-02 19:25:24
【问题描述】:

我正在使用 ASP.NET Core Web API。我有这个代码:

视图模型(Dto):

public class MandateDto
{
    public DateTime DueDate { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public int? MandateId { get; set; }
}
public class TransactionDto
{
    public string? RawData { get; set; }
}

实体映射器:

public class EntityMapper
{
    public Mandate FromMandateDtoToMandate(MandateDto mandate)
    {
        Mandate mandate = new Mandate()
        {
            DueDate = mandate.DueDate,
            StartDate = mandate.StartDate,
            EndDate = mandate.EndDate
        };
        string jsonString = JsonSerializer.Serialize(mandate);
        return mandate;
    }

    public TransactionLog FromMandateDtoToTransactionLog(TransactionDto mandate)
    {
        return new TransactionLog
        {
            RawData = jsonString,
        };
    }
}

授权服务:

    public async Task<Mandate> Post(MandateDto mandate)
    {
        var mapper = new EntityMapper();
        var mandate = mapper.FromMandateDtoToMandate(mandate);
        var transaction = mapper.FromMandateDtoToTransactionLog(mandate);

        try
        {
            await _unitOfWork.MandateRepository.Insert(mandate);
            await _unitOfWork.TransactionRepository.Insert(transaction);
            await _unitOfWork.SaveChangesAsync();
        }
        catch (Exception e)
        {
            throw new Exception(e.Message);
        }

        return mandate;
        return transaction;
    }

EntityMapper 所示,我想将 jsonStringFromMandateDtoToMandate 转移到 FromMandateDtoToTransactionLog 中,如下所示:

原始数据 = jsonString

我收到了这个错误:

错误 CS0103 当前上下文中不存在名称“jsonString”

我该如何解决这个问题?

谢谢。

【问题讨论】:

  • 您的 FromMandateDtoToTransactionLog 方法没有称为 jsonString 的参数/变量,所以这就是它无法编译的原因。
  • 您的 jsonString 变量在另一个方法中声明,在您尝试访问它的地方不可用。您应该阅读有关变量范围的信息。
  • JsonSerializer.Serialize(mandate) 移动到FromMandateDtoToTransactionLog;无论如何,你没有在FromMandateDtoToMandate 中使用jsonString
  • @MartinCostello - 我该怎么办?
  • @JohnathanBarclay - FromMandateDtoToTransactionLog 和 FromMandateDtoToMandate 有不同的模型。 jsonString 由在 FromMandateDtoToMandate 中完成的 Mandate 模型中的所有属性生成。

标签: c# asp.net-core asp.net-web-api


【解决方案1】:

您必须使用jsonString 添加此行,否则此范围内不存在该变量

public TransactionLog FromMandateDtoToTransactionLog(MandateDto mandate)
{
    string jsonString = JsonSerializer.Serialize(mandate); //add this line!
    return new TransactionLog
    {
        RawData = jsonString,
    };
}

【讨论】:

    猜你喜欢
    • 2021-03-05
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多