代码之家  ›  专栏  ›  技术社区  ›  Chris James

ASP.NET MVC已发布实体未映射到LINQ模型

  •  2
  • Chris James  · 技术社区  · 15 年前

    我的“用户”类有一个强类型的页面。当它被加载时,我从数据库中按ID加载它并将其传递给视图。

    当发布编辑表单时,对象将与其他一些参数一起发布到控制器方法fine。对象的属性由表单填充,但其ID(显然不在表单上)不会被发布。

    即使在代码中手动将其设置为ID并尝试保存上下文,数据库上也不会发生任何事情。

    下面是代码的大致视图,其中包含为简洁而删除的内容。

    public ActionResult MyProfile()
    {
        ViewData["Countries"] = new SelectList(userService.GetCountries(), "id", "name");
        return View(userService.GetById(CurrentUser.id));
    }
    
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult MyProfile(MSD_AIDS_Images_Data.LINQRepositories.User user, string password2)
    {
        user.id = CurrentUser.id;  //user id isn't posted, so need to reassign it
    userService.SaveChanges();
    }
    

    我已经写过很多次这样的代码,而且它已经工作了,出了什么问题?

    编辑

    调试用户对象时,它的propertyChanged和propertyChanging属性设置为空。

    2 回复  |  直到 15 年前
        1
  •  1
  •   dso    15 年前

    进入MyProfile方法的用户对象与Linq上下文没有关联。您需要使用显式绑定 UpdateModel ,例如:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult MyProfile(int id, string password2)
    {
        MSD_AIDS_Images_Data.LINQRepositories.User user = <LINQ query to load user by id>;
    
        UpdateModel(user); // updates the model with form values
    
        userService.SaveChanges();
    }
    

    注意,您可以在调用控制器方法之前实现一个自定义模型绑定器,这样您就可以接受用户作为参数,但我假设您还没有这样做。

        2
  •  0
  •   Chris James    15 年前

    我通过使用更新模型重载修复了模型绑定问题,该重载允许您指定要更新的模型中的哪些属性:

        string[] includeProperties = {"password", "firstname", "lastname", "email", "affiliation", "countryId"};
        UpdateModel(user, includeProperties);