user3756817
user3756817

Reputation: 324

Update an entity using entity framework while ignoring some properties

I am working with asp.net mvc 4. I have to update my persistence store using an edit method, but I want to ignore some columns.

I had found some answers here, but they weren't working for me (I suppose).

Here is my method:

[HttpPost]
public ActionResult Edit(Candidat candidat)
{
    ProcRecDB _db = new ProcRecDB();  //  from DbContext

    if (ModelState.IsValid)
    {

        _db.Entry(candidat).State = EntityState.Modified;
        _db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(candidat);
}

The Candidate model has 10 properties; how would I ignore some of them?

Upvotes: 3

Views: 8176

Answers (4)

T3.0
T3.0

Reputation: 496

Say you have an object with 10 properties and you only want to update one. First, as expected, the client-side .cshtml form should only contain the field(s) you are updating as well as the ID. Secondly, in the post method do the following:

// Form Data Model
public Candidate FormCandidate {get; set;}

public IActionResult OnPostCanidata() {
    var _update = _context.Candidate.Find(Id);
    _update.SomeProperty = FormCandidate.SomeProperty;
    _context.SaveChanges();
}

I prefer this method over the "Property/isModified" approach because if 9 out of 10 fields don't get updated that's a lot of extra server side code to write. Also if the data model changes and additional read-only properties are added, you won't need to re-visit the code and specify their Property/isModified=fasle.

Upvotes: 0

codebased
codebased

Reputation: 7073

You are in same position has me. I have similar things to do.

You have to options:

You can use NotMapped (in case you don't want to store any value ).

However I think you want this:

if it is readonly, and you don't want to modify then you can do something similar:

var attachedEntity = this.context.Entry(orignalEntity);
                    attachedEntity.CurrentValues.SetValues(updatedEntity);

    List<string> excludeProperties = new List<string>();

                        // Some of these fields you cannot just modify at all.
                        excludeProperties.Add("UniqueIdentifier");
                        excludeProperties.Add("AuthorID");
                        excludeProperties.Add("DateCreated");
                        // You could even ask your dervived calls to tell which one to exclude 
// excludeProperties.AddRange(this.ExcludeUpdateProperties());

                        foreach (var name in excludeProperties)
                        {
                            var property = attachedEntity.Property(name);
                            if (property != null)
                            {
                                attachedEntity.Property(name).IsModified = false;
                            }
                        }

with this approach, rather than updating those fields that needs to be updated you can use attachedEntity.CurrentValues.SetValues(updatedEntity) which will set all value as new value, and then you can exclude that you want to. This approach is nicer than updating each field one by one.

Upvotes: 2

Teppic
Teppic

Reputation: 2546

You can create a new object, attach it to the db context, then update just the properties you want to be persisted.

[HttpPost]
public ActionResult Edit(Candidat candidat)
{
    ProcRecDB _db = new ProcRecDB();  //  from DbContext

    if (ModelState.IsValid)
    {
        var updatedCandidat = new Candidat { Id = candidat.Id };

        _db.Attach(updatedCandidat);

        // Set the properties that you would like to update. This must be
        // done after the object has been attached to the db context.
        updatedCandidat.FirstName = candidat.FirstName;
        updatedCandidat.LastName = candidat.LastName;
        ...

        _db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(candidat);
}

Upvotes: 3

user3559349
user3559349

Reputation:

If your using EF 5, you can mark a property as not modified after its been marked as modified

_db.Entry(candidat).State = EntityState.Modified;
// Ignore changes to the value of SomeProperty
_db.Entry(candidat).Property("SomeProperty").IsModified = false;
_db.SaveChanges();

Upvotes: 10

Related Questions