简体   繁体   中英

C# automapper core Dictionary<string, object>

I have a dbo table Records like:

CREATE TABLE records (
    key VARCHAR(100) NOT NULL,
    value_decimal DECIMAL(10, 5) NULL,    
    value_date DATETIME NULL
)

EF Core maps this table into class record like this:

public class record {
    public string key {get; set;}
    public decimal? value_decimal {get; set;}
    public DateTime? value_date {get; set;}
}

And finally API returns Dictionary<string, object> like:

[HttpGet]
public Dictionary<string, object> getRecords() 
{
    return this.IRepository.records.ToDictionary(
                                         d => d.key, 
                                         d => (object) new { 
                                                value_date = d.value_date,
                                                value_decimal = d.value_decimal 
                                             });
}

This works just fine, result is used in JavaScript like records["some_key"].value_decimal . Perfect!

Now I need [HttpPost] method which receives modified dictionary from JavaScript back and maps it to EF entity back. My deepest whishes look like:

[HttpPost]
public void saveRecords(Dictionary<string, object> payload)
{    
    var _records = this.IRepository.records.Where(w => /*some conditions*/);

    AutoMapper.Map<Dictionary<string, object>, Models.EF_Entities.record>(
                    _records, 
                    payload);

    this.IRepository.SaveChanges();
}

Has anyone done something like this?
Thanks!

Thanks to * for your effort. Problem has been solved by a workaround:

[HttpPost]
public void saveRecords(Dictionary<string, object> payload)
{    
    var _records = this.IRepository.records.Where(w => /*some conditions*/);

    foreach (var kvp in payload)
    {
        var _record = _records.Where(w => w.key == kvp.Key).FirstOrDefault();

        if (_record != null)
        {
            AutoMapper.Map(kvp.Value, _record);
        }
    }

    this.IRepository.SaveChanges();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM