3

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?

1
  • 1
    Have you tried the [NotMapped] attribute on the properties you want to ignore? Commented Sep 8, 2014 at 23:27

4 Answers 4

10

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();
Sign up to request clarification or add additional context in comments.

1 Comment

think you this is the best answer that what i was looking for.
3

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);
}

2 Comments

You should really use a using block
This is nice, and works.. :) Much easier than @codebased's answer which involves magic strings
2

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.

Comments

0

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.

3 Comments

There is a better solution: use a DTO object and update the entity by Entry(_update).CurrentValues.SetValues(dto);.
@GertArnold thanks. I did some brief research on the topic after reading your comment. Definitely seems like a better approach. Suppose I was developing a web application with the requirement of 3 separate user interfaces, each interface modifying the same type of object but a different set properties. If I wanted to use the DTO approach to meet this requirement would I build 3 separate DTOs to accommodate each interface?
Yep, that's the idea. That's one of the few drawbacks of C# being a typed language.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.