Home > front end >  Dynamic property name to update
Dynamic property name to update

Time:10-30

I have DB with columns: Id, DataA, DataB, DataC and there are may be more data columns. I have api endpoint where I pass Id and column data name and I should update this data column with current UTC time. One request one list of ids and all ids update with same UTCtime.

...
switch (model.ColumnName)
{
    case "DataA":                               
    queriedContext.Select(x => { x.DataA = DateTime.UtcNow; return x; }).ToList();
        break;
    case "DataB":                               
    queriedContext.Select(x => { x.DataB= DateTime.UtcNow; return x; }).ToList();
        break;
    default:
        break;
}
...

Is it possible remove repeatable LINQ in switch and change to something smart?

CodePudding user response:

You should not use LINQ to cause side-effects that update something. LIN(Q) is to query a source not to modify it. For that use a foreach:

DateTime utcNow = DateTime.UtcNow;
foreach(var x in queriedContext)
{
    switch (model.ColumnName)
    {
        case "DataA":                               
            x.DataA = utcNow;
            break;
        case "DataB":                               
            x.DataB = utcNow;
            break;
        default:
            break;
    }
}

You could make it little bit "more elgant" by re-using the same action, because the column-name will not change in the loop, so you don't need the switch there. So create this as (local) method:

Action<Data> GetUpdateDateColumn(string column, Func<DateTime> getDate)
{
    switch (column)
    {
        case "DataA":                               
            return x => x.DataA = getDate();
        case "DataB":                               
            return x => x.DataB = getDate();
        default:
            return null;
    }
}

Now you can use this action in the foreach:

DateTime utcNow = DateTime.UtcNow;
Action<Data> updateDateColumn = GetUpdateDateColumn(model.ColumnName, () => utcNow);
if(updateDateColumn == null) return; // not a valid column
   
foreach(Data x in queriedContext)
{
    updateDateColumn(x);
}
  • Related