How to create new entity object, modify it in Model before SaveChanges()

巧了我就是萌 提交于 2021-02-08 03:28:11

问题


I've been dwelling with this issue for hours and couldn't figure out the problem. So I'm using ASP.NET MVC 3 with Entity Framework 4.1. I am writing the account management controller and models from scratch. My problem is that whenever the Controller receives the filled-up entity object from the View and sends it onwards to the Model, the Model won't save it if I try to modify any of the fields beforehand.

Here is the relevant portion of my model, named ModelManager.cs :

public class MemberManager
{
    private DAL db = new DAL();

    public void Add(Member member)
    {
        member.Password = Crypto.HashPassword(member.Password);
        db.Members.Add(member);
        db.SaveChanges();
    }

That model gets the Member member entity object as a parameter from the Controller, relevant portion of-which is below:

    [HttpPost]
    public ActionResult Register(Member member)
    {
            try
            {
                if (ModelState.IsValid)
                {
                    MemberManager memberManager = new MemberManager();
                    if (!memberManager.UsernameExist(member.Username))
                    {
                        memberManager.Add(member);
                        FormsAuthentication.SetAuthCookie(member.FirstName, false);
                        return RedirectToAction("Welcome", "Home");
                    }
                    else
                    {
                        ModelState.AddModelError("", "Username already taken.");

                    }
                }
            }
            catch
            {
                ModelState.AddModelError("", "Could not complete account creation. Please try again.");
            }

            return View(member);
    }

If I remove any modification to any property of the entity object in the Model, the code works (i.e. I remove the line where I Crypto.HashPassword the entity object's Password field. At first I thought the issue was with HashPassword, but if I change that line to simply change the member.Password to string "1", it won't work either.

So, what am I doing wrong? I'm entirely new to programming so bear with me if the issue is quite flagrant. Isn't it possible to create an entity object from the View upon account creation, send it through to the Controller that then passes it on to the Model which modifies the Password to hash it before saving it?

BTW, the exception error raised is:

System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. at System.Data.Entity.Internal.InternalContext.SaveChanges() at System.Data.Entity.Internal.LazyInternalContext.SaveChanges() at System.Data.Entity.DbContext.SaveChanges() at Politiq.Models.ObjectManager.MemberManager.Add(Member member) in C:\Users\C. Yehia\Documents\Visual Studio 2010\Projects\Politiq2\Models\ObjectManager\MemberManager.cs:line 21 at Politiq.Controllers.AccountController.Register(Member member) in C:\Users\C. Yehia\Documents\Visual Studio 2010\Projects\Politiq2\Controllers\AccountController.cs:line 39


回答1:


I see your member instance being created by a model binder (i.e. not in your code) but I don't see it actually being added to the table. Did you miss db.Members.Add() call?

Anyway, I would suggest creating a separate model class for “registration data” so you don't let MVC model binder create Member instance but instead create it yourself. The reason is this approach is insecure because by default the binder will try to assign each HTML input field to a matching property so a hacker can inject Id value in your object that will cause an exception (and probably some other nasty things).

Of course, you can use [Bind(Exclude="ID")] so it doesn't try to fill the ID but I would still separate database entities and user input:

MemberController

public ActionResult Register(RegistrationForm form)

MemberManager

public Member RegisterMember(RegistrationForm form)


来源:https://stackoverflow.com/questions/6932148/how-to-create-new-entity-object-modify-it-in-model-before-savechanges

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!