Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude Property on Update in Entity Framework

I've been looking for a proper way to mark a property to NOT be changed when updating a model in MVC.

For example, let's take this small model:

class Model {     [Key]     public Guid Id {get; set;}     public Guid Token {get; set;}      //... lots of properties here ... } 

then the edit method MVC creates looks like this:

[HttpPost] public ActionResult Edit(Model model) {     if (ModelState.IsValid)     {         db.Entry(model).State = EntityState.Modified;         db.SaveChanges();         return RedirectToAction("Index");     }     return View(model); } 

now if my View does not contain the Token, it will be nullified through that edit.

I'm looking for something like this:

db.Entry(model).State = EntityState.Modified; db.Entry(model).Property(x => x.Token).State = PropertyState.Unmodified; db.SaveChanges(); 

The best way so far I found is to be inclusive and set all properties I want included by hand, but I really only want to say which ones to be excluded.

like image 893
Manuel Schweigert Avatar asked Sep 30 '12 14:09

Manuel Schweigert


People also ask

What is EntityState modified?

EntityState.Added : EntityState.Modified; context.SaveChanges(); } } Note that when you change the state to Modified all the properties of the entity will be marked as modified and all the property values will be sent to the database when SaveChanges is called.

What is not mapped in C#?

The NotMapped attribute is used to specify that an entity or property is not to be mapped to a table or column in the database. In the following example, the AuditLog class will not be mapped to a table in the database: public class Contact. {


1 Answers

we can use like this

 db.Entry(model).State = EntityState.Modified;  db.Entry(model).Property(x => x.Token).IsModified = false;  db.SaveChanges(); 

it will update but without Token property

like image 198
Nitin Dominic Avatar answered Sep 20 '22 20:09

Nitin Dominic