MVC 3 / EF 4.2 - 针对ViewModel进行编辑,是否可以针对Model或ViewModel进行保存?

时间:2012-02-10 06:20:59

标签: asp.net-mvc-3 save entity viewmodel

我的第一个MVC3 EF 4.2网站,我对一些事情感到困惑,目前在ViewModels查询和保存时。如果我解释得不好,请纠正我,我不知道怎么说这个。 .edmx自动创建了表类,但我认为最好创建一个ViewModel,考虑到我需要连接表来完全显示/编辑我的产品。下面的控制器代码是我连接表以输出要编辑的产品然后保存的地方。我的问题 - 将产品保存到DbContext或我自己的ProductViewModel.cs生成的Product.cs模型的正确方法是什么?

是否有更简单的方法来查询产品并加入表格然后映射到viewmodels参数,或者我是否继续在控制器中执行所有这些操作,如下所示?

我还想在每次有人查看/点击产品时保存/更新产品,因此我不确定是否创建单独的ViewModel以仅更新该参数或再次使用产品型号。

希望有道理!如果需要,我可以进一步解释。

private SiteForgeEntities db = new SiteForgeEntities();

public ActionResult Edit(int id)
    {
        var viewModel = (
            from a in db.Products
            join b in db.Sites
            on a.SiteId equals b.SiteId
            join c in db.Sections
            on a.SectionId equals c.SectionId
            join d in db.Affiliates
            on a.AffiliateId equals d.AffiliateId
            select new ProductViewModel()
            {
                ProductId = a.ProductId,
                Product = a.Product,
                Description = a.Description,
                Image = a.Image,
                Price = a.Price,
                Clicks = a.Clicks,
                Link = a.Link,        
                Site = b.Site,
                Section = c.Section,
                Affiliate = d.Affiliate
            }).Single(x => x.ProductId == id);      

        return View(viewModel);
    }

    [HttpPost]       
    public ActionResult Edit(Product product)
    {
     ...update database...do I pass in and save back to Product or my ProductViewModel
    }

1 个答案:

答案 0 :(得分:0)

使用ViewModel将多个模型传递给视图,但是在保存数据时,需要将其保存到适当的模型中。如果要添加或修改产品,则会向产品添加项目(使用DbContext)。如果在两个模型之间定义了一对多关系(在Product.cs模型中,您可能将属性声明为:

public virtual ICollection<SomeOtherModel> SomeOtherData { get; set; }

您可以使用它来构建表,而不是在ViewModel中传递所有内容。这里有一个关于使用EF4的CRUD操作的很好的教程。看看这些简短的教程,可以让您了解您的策略http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc

相关问题