如何将我的模型数据(列表)映射到另一个视图模型数据(列表)MVC asp.net

How to map my model data (list) with another viewmodel data (list) MVC asp.net

在这种情况下如何将我的模型数据(列表)映射到另一个视图模型数据(列表)?

这是我的:

我的 json 视图模型

public class JsonViewModel
{
    public List<JsonItem> Items { get; set; } 
}

public class JsonItem
{
    public string Name { get; set; }
    public int Unit { get; set; }
    public decimal Price { get; set; }
    public IEnumerable<Item> ItemStock { get; set; } 
}

我的主要模特

public class Item
{
    public int ItemId { get; set; }
    public string Name { get; set; }
    public int QuantityInPack { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
    public bool IsHidden { get; set; }
}

应该这样映射:

其中 Item.Name = JsonItem.Name


控制器

public ActionResult Index()
{
    // 1. Perform HTTP request to retrieve the JSON.
    var webClient = new WebClient();
    string rawJson = webClient.DownloadString("http://my_json_data");

    // 2. Parse the JSON.
    var jsonRootObject = JsonConvert.DeserializeObject<JsonViewModel>(rawJson);

    // 3. Map to viewmodel
    var viewModel = new JsonViewModel
    {
        Items = jsonRootObject.Items.Select(i => new JsonItem
        {
            Name = i.Name,
                    Unit = i.Unit,
                    Price = i.Price
        }).ToList()
    };



    /// var TestItem = db.Items.ToList();
    /// TestItem.QuantityInPack = JsonItem.Unit
    /// TestItem.Price = JsonItem.Price
    ///     where Item.Name = JsonItem.Name
    ///
    /// (I know it's a bad, but I wanted to explain what I mean)
    /// Here i should map data in some way
    /// 
    ///

    // 4. Return mapped model to view
    return View( TestItem??? );
}

如果我明白你想要什么并且 db 表示 dbContext,试试这个:

var names = viewModel.Items.Select(x => x.Name).ToList(); 
var TestItems = db.Items.Where(x => names.Contains(x.Name)).ToList();

var result = (from item in TestItems 
             join json in viewModel.Items on item.Name equals json.Name
             into subJsons from subJson in subJsons.DefaultIfEmpty() 
             select new { item, subJson }).ToList().
             Select(x => {
                  var newItem = x.item;
                  if(subJson != null)
                  {
                       newItem.QuantityInPack = x.subJson.Unit; 
                       newItem.Price = x.subJson.Price;
                  }
                  return newItem;
             }).ToList();

 return View(result);

如果我没理解错的话,你想JsonViewModel与主模型同步,return同步主模型来查看:

public ActionResult Index()
{
    ...
    var itemList = db.Items.ToList();
    if (jsonRootObject.Items != null)
    {
        jsonRootObject.Items.ForEach(i =>
        {
            var item = itemList.FirstOrDefault(p => p.Name = i.Name);
            if (item != null)
            {
                item.QuantityInPack = i.Unit;
                item.Price = i.Price;
            }
        });
    }
    return View(itemList);
}