C#-从持久性存储中检索数据并将其保存到视图模型 [英] C# - Retrieve data from persistence storage and save it to the view model

查看:95
本文介绍了C#-从持久性存储中检索数据并将其保存到视图模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我有一个控制器方法,我想返回看起来像这样的视图模型

Hello I have a controller method that I want to return the view model of that looks like this

这是经过硬编码的样子

 public ActionResult SpecialOrderSummary(int? id)
        {
            // Retrieve data from persistence storage and save it to the view model.
            // But here I am just faking it.
            var vm = new ItemViewModel
            {
                ItemId = 123,
                ItemName = "Fake Item",
                Parts = new List<ItemPartViewModel>
                {
                    new ItemPartViewModel
                    {
                        PartId = 1,
                        PartName = "Part 1"
                    },
                    new ItemPartViewModel
                    {
                        PartId = 2,
                        PartName = "Part 2"
                    }
                }
            };

            return View(vm);
        }

但是我显然不希望它被硬编码.所以这就是我要努力实现的目标

But I obviously don't want it hard coded. So this is what I was trying to do instead to achieve my goal

  public ActionResult SpecialOrderSummary(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            JobOrder jobOrder = db.JobOrders.Find(id);
            if (jobOrder == null)
            {
                return HttpNotFound();
            }
            ViewBag.JobOrderID = jobOrder.ID;
            ItemInstance ii = db.ItemInstances.Where(x => x.serialNumber == jobOrder.serialNumber).FirstOrDefault();
            Item item = db.Items.Find(ii.ItemID);

            var vm = new ItemViewModel
            {
                ItemId = item.ItemID,
                ItemName = item.Name,
                Parts = new List<ItemPartViewModel>
                {
                  foreach(ItemHasParts ihp in item.IHP) 
                   {
                     Part part = db.Parts.Find(ihp.PartID);
                     new ItemPartViewModel
                     {
                        PartId = part.ID,
                        PartName = part.Name
                     };
                   }
                }
             };

            return View(vm);
        }

但这不起作用.由于似乎无法识别结束} 开头的零件"部分以及开头的"vm"括号,因为它同时跳过了两者.为什么会这样?

But that doesn't work. As it doesn't seem to recognize the closing } of the opening "Parts" and the opening "vm" bracket as it skips both. Why is this?

推荐答案

嗯,我想我之前回答了这个问题: https://stackoverflow.com/a/62782124/2410655 .基本上,视图模型中间不能有for循环.

Hmmm I thought I answered this question before: https://stackoverflow.com/a/62782124/2410655. Basically you can't have a for loop like that in the middle of the view model.

我想再添加2件事.

如果特殊订单摘要需要ID,请不要将其声明为可选.如果这样做,则必须添加更多逻辑以检查是否存在ID.

If the special order summary expects an ID, don't declare it as optional. If you do so, you have to add more logic to check whether there is an ID or not.

如果订单摘要需要一个ID,只需将其声明为int id.如果客户端不提供它,则让MVC框架处理该错误.现在,根据您的设置,您的MVC可能会抛出404或500或用户友好的页面.由开发人员来决定.

If the order summary expects an ID, just declare it as int id. And if the client doesn't provide it, let the MVC framework handle the error. Now depending on your setup, your MVC might throw a 404, or 500, or a user-friendly page. It's up to you, the developer, to set it up.

在您的代码示例中,我看到您在项目实例上使用了FirstOrDefault().如果返回为NULL并调用db.Items.Find(ii.ItemID) ...

In your code example, I see you used FirstOrDefault() on the item instance. That will bite you if it comes back as NULL and you call db.Items.Find(ii.ItemID)...

因此,根据您的示例,我将代码更改为:

So based on your example, I would change the code to:

public ActionResult SpecialOrderSummary(int id)
{
    JObOrder jobOrder = db.JobOrders.Find(id);
    if (jobOrder == null)
    {
        return HttpNotFound();
    }

    ItemInstance itemInstance = db.ItemInstances
        .Where(x => x.serialNumber == jobOrder.serialNumber)
        .FirstOrDefault();

    Item item = null;
    if (itemInstance != null)
    {
        item = db.Items.Find(itemInstance.ItemID);
    }

    var vm = new JobOrderSummaryViewModel
    {
        JobOrderId = jobOrder.ID,
        Parts = new List<ItemPartViewModel>();
    };

    if (item != null)
    {
        vm.ItemId = item.ItemId;
        vm.ItemName = item.ItemName;

        foreach(ItemHasParts ihp in item.IHP) 
        {
            // Does Part and Item have many-to-many relationships?
            // If so, you might be able to get the part by
            // ihp.Part instead of looking it up using the ID.
            // Again, it depends on your setup.
            Part part = db.Parts.Find(ihp.PartID);

            if (part != null)
            {
                vm.Parts.Add(new ItemPartViewModel
                {
                    PartId = part.ID,
                    PartName = part.Name
                });
            }
        }
    }

    return View(vm);
}

注意:

您还可以在循环(db.Parts.Find(ihp.PartID);)内附加调用数据库.如果您有大量数据,那将导致性能问题.您有什么方法可以一开始就提取所需的所有数据吗?

Note:

You have additional calls back to the database inside the loop (db.Parts.Find(ihp.PartID);). That will cause performance issue if you have huge data. Is there any way you can fetch all your data you needed once at the beginning?

这篇关于C#-从持久性存储中检索数据并将其保存到视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆