0

Say, I have a model Car with these properties (for simplicity, I skipped get/set):

string Name;    // user can change
string Secret;  // user cannot change
DateTime CreatedAt = DateTime.Now;  // even we cannot change

Then in ASP Web Application 3.1, the scaffold generates Edit.cshtml.cs with this contents (simplified):

[BindProperty]
public Car Car { get; set; }
public Task<IActionResult> OnPost()
{
    _context.Attach(LanguageExporter).State = EntityState.Modified;
    _context.SaveChanges();
    // redirect ...
}

So it allows a user to make POST with all the fields of Car.

But actually, I would like to ignore CreatedAt completely and not allow changing Secret from POST parameters (but allow from code). [BindNever] does not help since ASP skips Secret and it keeps default(string) => null on it which I don't want. For CreatedAt it keeps default(DateTime) => 01.01.0001.


So I am appealing to the community with the question, how can I automate the process of editing my models?

As I see it, ASP should ignore some POST parameters and EF should ignore updating some properties. Or ASP should fetch the model first and change only particular properties (e.g. keep CreatedAt).

What are the best practices out there in this situation?

1
  • That's pretty opinion based, but OK, just don't mark the entire entity as modified, only specific properties. Commented Jul 7, 2020 at 18:41

2 Answers 2

3

If you want to ignore the CreatedAt when edit, you can make the IsModified property of it as false like below:

_context.Attach(Car).State = EntityState.Modified;
_context.Entry<Car>(Car).Property(x => x.CreatedAt).IsModified = false;
Sign up to request clarification or add additional context in comments.

Comments

2

When you are creating an API, you should use a ViewModel, which is not the database entity, but a representation of the properties that are required by the request.

For example, if you allowed the user to edit the user's name and phone number, then your view model would only contain those 2 properties (even though the 'user' database entity may contain many more). Then you would find the database record to update, only change the properties you need to change, and then save the changes.

class EditViewModel
{ 
   public int Id {get;set;}
   public string Name {get;set;}
   public string PhoneNumber {get;set;}
}

[BindProperty]
public EditViewModel ViewModel {get;set;}

public void OnPost()
{
    var entity = _context.Single(x=>x.Id == ViewModel.Id);
    entity.Name = ViewModel.Name;
    entity.PhoneNumber = ViewModel.PhoneNumber;
    _context.SaveChanges();
}

}

Comments

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.