开发者

how can to instruct entity framework not to update a property of a model

开发者 https://www.devze.com 2023-04-13 00:48 出处:网络
I am using Asp.net MVC and Entity framework(Below code is just for demo) I have a model like below public class Person

I am using Asp.net MVC and Entity framework (Below code is just for demo)

I have a model like below

  public class Person
    {
        [Key]
        public int Id { get; set; }

        [Required]
        public string FirstName { get; set; }

        /*Time at which person was created*/
        public DateTime CreatedOn { get; set; }  /*should not change once created*/
    }

At the time of creating + inserting new person, i manually set CreatedOn datetime property.

On Update

My View only has one textbox

 @using (Html.BeginForm())
        {
            @Html.LabelFor(a => a.FirstName) 
            @Html.EditorFor(a => a.FirstName) 
            @Html.ValidationMessageFor(a => a.FirstName)            
            <br />
            <input type="submit" name="name" value="submit" />
}

Controller

    [HttpPost]
    public ActionResult EditPerson(Person person)
    {
        if (ModelState.IsValid)
        {
            db.Entry(person).State = EntityState.Modified;
            db.SaveChanges();

            /* ----------------
              Error here
              ----------------- 
             */

            return RedirectToAction("ListPerson");
        }
        return View(person);            
    }

I am getting error at mentioned point in my code , error: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. Error seems obvious as person object received inside controller has default time-value, and entity framework tries to update that field too.

My question is how can i instruct entity framework not to update a property. Suppose in above case if for CreatedOn property i say to entity framework do not update it, i wont get error.

I tried [Editable(false)] attribute on CreatedOn but it didn't work.

There are some options like , before updating i first load the exis开发者_JS百科ting entity from Database and copy createdOn property.....

I want you know that in my real model there many properties that i dont want to update and there are many such models, so I am expecting some realistic answers.

Edit 1

I am using code first.


The specific error you're getting is because the CreatedOn is being set to the default value. When you do your postback you'll have to load the object from the database, update it and then save it. By doing that you'll stop this particular error that you're experiencing.

It appears that you're using your entity model as the model in your controller. I wouldn't recommend this. By creating a model specifically for the post you can remove any non-editable fields from your model. Then you would copy the model values from the ViewModel to your Entity model. This prevents users from editing properties that you might not want them to edit.

public class PersonViewModel
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string FirstName { get; set; }
}

The main reason this is a good idea is that someone may try to guess what values might also work. For instance, if you had a property on your Person object called IsAdministrator and I were to intercept the post and add &IsAdministrator=on&Adminstrator=on&Admin=on (to cover a few bases) then the ModelBinder will take that value and apply it to the model. Now I've just become an administrator in your system. I realize this is a lot of work if you have a lot of models but it's never a good idea to use your entity models for posts.

You can also use the Bind attribute to limit the items bound by the mapper.

public ActionResult EditPerson([Bind(Exclude = "CreatedOn")] Person person)

This should prevent the binder from binding that particular property. However it won't fix your problem since when the person object is created the default value is always set. The only way to fix this is to load your object from the database and then update/save it.

0

精彩评论

暂无评论...
验证码 换一张
取 消