Dmitry Tabakerov February 2016

Read-only field after INSERT with EF

Entity Framework, Code First

I have a model with a lot of fields. One field ("Name") I do not want to be editable but read-only after insert. But I still want to show this field as part of my "Edit" form (and viewModel for edit). I'd like to show it as readonly textbox (like @Html.TextBoxFor(c => c.Name, new {@readonly = "readonly"})) but if someone change it's value with browser dev.tools it should not be saved to DB.

Is there some beautiful way to do it?

Now I'm getting an instance from DB on and set "Name" field of form data back to value from DB.

Answers


kadoga February 2016

When processing the ViewModel which is sent from the frontend, ignore the "read-only" fields before saving them in the database. AFAIK EF does not support ignoring of properties.


IMAO510 February 2016

One way to approach this using Entity Framework is to create a database model and a view model. Make sure you have the CRUD translation in the back end when saving.

public async Task<YourModelContext> SaveModel(YourModelContext context)
{
  var existing = await YourTable.FirstOrDefaultAsync(f => f.Id == context.Id);
  if (existing == null)
  {
    existing = new YourDatabaseModel
    {
      Created = DateTime.UtcNow
    }

    YourTable.Add(existing);
  }

  // Name will be saved and changed by the user
  // existing.Name = context.Name;
  // existing.Description = context.Description;
  // existing.SomeOtherField = context.SomeOtherField;

  // Not specifying name will not update the name.
  // You'll have to set the readonly on textbox in the web page
  existing.Description = context.Description;
  existing.SomeOtherField = context.SomeOtherField;

  // Save the changes to the underlying database
  await SaveChangesAsync();

  // Assign the inserted database id to the view model id
  context.Id = existing.Id;

  // Return the view model context to the html page
  return context;
}

Post Status

Asked in February 2016
Viewed 2,130 times
Voted 13
Answered 2 times

Search




Leave an answer