Home > database >  How to write more elegant mapping of these conditions?
How to write more elegant mapping of these conditions?

Time:09-01

I have 40 datasets, but when user click some of them I need to map their ID's to another dataset:

 public async Task<PagedResult<DataSetUpdateViewModel>> Handle(GetDataSetUpdateByDataSetIdQuery request, CancellationToken cancellationToken)
    { //this I need to refactor
     if(request.ID==29)
        {
            request.ID = 28;
            request.DeleteAble = true;
        }
      if(request.ID==30)
        { request.ID=31;
          request.DeleteAble = true;
        }
      if(request.ID==32)
        { request.ID=31;
          request.DeleteAble = true;
        }
      if(request.ID==33)
        { request.ID=31;
          request.DeleteAble = true;
        }
        //if request.ID is not 29,30,32 or 33, then it should be pass as it is
        var datasetUpdates = _context.DatasetUpdates
        .Where(c => request.ID > 0 && c.DatasetId == request.ID)
        .ProjectTo<DataSetUpdateViewModel>(_mapper.ConfigurationProvider,new { isDeleteAble = request.DeleteAble });
         

        PagedResult<DataSetUpdateViewModel> result = new PagedResult<DataSetUpdateViewModel>();
        result = await datasetUpdates.DynamicOrderBy("UpdateDate", "DESC")
                        .GetPagedAsync(request.PageNumber, request.PageSize, cancellationToken);
        return result;

    }

My GetDataSetUpdateByDataSetIdQuery looks like

    public int ID { get; set; }
    public int PageNumber { get; set; }
    public int PageSize { get; set; }
    public bool DeleteAble { get; set; }

I know I can assign Enums to these numbers, but it still does not solve a lot of if conditions

CodePudding user response:

Use a simple Dictionary<int, int>:

internal static Dictionary<int, int> _queryMapping = new Dictionary<int, int>
{
    {29, 28},
    {30, 31},
    {32, 31},
    {33, 31}
}

// ...

public async Task<PagedResult<DataSetUpdateViewModel>> Handle(GetDataSetUpdateByDataSetIdQuery request, CancellationToken cancellationToken)
{
    if(_queryMapping.ContainsKey(request.ID)){
        request.ID = _queryMapping[request.ID];
        request.DeleteAble = true;
    }

    // ...
}

CodePudding user response:

Use a Datatable for lookup :

            DataTable dt = new DataTable();
            dt.Columns.Add("old id", typeof(int));
            dt.Columns.Add("new id", typeof(int));
            dt.Columns.Add("deletable", typeof(Boolean));

            dt.Rows.Add(new object[] { 29, 28, true });
            dt.Rows.Add(new object[] { 30, 31, true });
            dt.Rows.Add(new object[] { 32, 31, true });
            dt.Rows.Add(new object[] { 33, 31, true });

            DataRow searchResults = dt.AsEnumerable().Where(x => x.Field<int>("old id") == 32).FirstOrDefault();

            int newId = searchResults.Field<int>("new id");
  •  Tags:  
  • c#
  • Related