Codecademy Logo

ASP.NET Data Edits

Related learning

  • Learn how to build fast, secure, and maintainable web apps with ASP.NET and the Razor Pages architecture.
    • With Certificate
    • Intermediate.
      17 hours
  • Jumpstart your career with this skill path, first by learning the C# language, then building web apps with ASP.NET Core and the Razor Pages.
    • Includes 7 Courses
    • With Certificate
    • Intermediate.
      41 hours

Model Binding

In ASP.NET Core, model binding is a feature that simplifies capturing and storing data in a web app. The process of model binding includes retrieving data from various sources, converting them to collections of .NET types, and passing them to controllers/page models. Helpers and attributes are used to render HTML with the contents of bound page models. Client- and server-side validation scripts are used to ensure integrity during data entry.

Adding Records

The Entity Framework context DbSet member provides the Add() and AddAsync() methods to insert a new record into the in-memory representation of the corresponding database table. A batch of multiple records can also be added in this fashion.

The record is passed from the browser in the <form> post back. In this case a Country member is declared with a [BindProperty] attribute so the entire record is passed back to the server.

Use the EF context SaveChanges() or SaveChangesAsync() methods to persist all new records to the database table.

// Assuming Country is of type Country
// Assuming _context is of a type inheriting DbSet
public async Task<IActionResult> OnPostAsync(string id)
{
if (!ModelState.IsValid)
{
return Page();
}
await _context.Countries.AddAsync(Country);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}

Saving Changes

The Entity Framework context DbSet member provides the Attach() method to update an existing record, the Add() method to insert a new record, and the Remove() method to delete an existing record. Any combination of multiple records can batched before saving.

Use the EF context SaveChanges() or SaveChangesAsync() methods to persist all inserted, updated, and deleted records to the database table.

// Assuming Country is of type Country
// Assuming _context is of a type inheriting DbSet
public async Task<IActionResult> OnPostAsync(string id)
{
// update
_context.Attach(Country).State = EntityState.Modified;
// insert
await _context.Countries.AddAsync(Country);
// delete
Country Country = await _context.Countries.FindAsync(id);
if (Country != null)
{
_context.Countries.Remove(Country);
}
// all three methods must be followed by savechanges
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}

Finding Records

The Entity Framework context DbSet member provides the Find() and FindAsync() methods to retrieve an existing record from the in-memory representation of the database table. Assign the result of this method to a local member in the page model.

This method generates the appropriate SQL syntax needed to access the record in the database table.

// Assuming Country is of type Country
// Assuming _context is of a type inheriting DbSet
public async Task<IActionResult> OnGetAsync(string id)
{
if (id == null)
{
return NotFound();
}
Country Country = await _context.Countries.FindAsync(id);
return Page();
}

Deleting Records

The Entity Framework context DbSet member provides the Remove() method to delete an existing record from the in-memory representation of the database table. Any combination of multiple record deletions can be batched before saving.

Use the EF context SaveChanges() or SaveChangesAsync() methods to persist all deletions to the database table.

// Assuming Country is of type Country
// Assuming _context is of a type inheriting DbSet
public async Task<IActionResult> OnPostAsync(string id)
{
if (id == null)
{
return NotFound();
}
Country Country = await _context.Countries.FindAsync(id);
if (Country != null)
{
_context.Countries.Remove(Country);
}
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}

Updating Records

The Entity Framework context DbSet member provides the Attach() method to update an existing record in the in-memory representation of the corresponding database table. A batch of multiple records can also be updated in this fashion.

The record is passed from the browser in the <form> post back. In this case a Country member is declared with a [BindProperty] attribute so the entire record is passed back to the server.

Use the EF context SaveChanges() or SaveChangesAsync() methods to persist all updated records to the database table.

// Assuming Country is of type Country
// Assuming _context is of a type inheriting DbSet
public async Task<IActionResult> OnPostAsync(string id)
{
if (!ModelState.IsValid)
{
return Page();
}
_context.Attach(Country).State = EntityState.Modified;
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}

Valid Model State

Entity Framework database models accept annotations that drive data validation at the property level. If you are using the asp-validation-for or asp-validation-summary HTML attributes, validation is handled client-side with JavaScript. The model is validated and the <form> post back won’t occur until that model is valid.

Sometimes the client-side validation will not be available so it is considered best practice to also validate the model server-side, inside the OnPostAsync() method. This example checks for ModelState.IsValid and returns the same page if it is false. This effectively keeps the user on the same page until their entries are valid.

If the model is valid, the insert, update, or delete can proceed followed by SaveChangesAsync() to persist the changes.

public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.Continents.Add(Continent);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}

LINQ Queries

The Entity Framework DbSet entities can manage complex queries using C# LINQ syntax. This is referenced from the System.Linq library.

All of the Where() and OrderBy() clauses are evaluated in the final statement that calls ToListAsync(). EF evaluates all options and generates a SQL SELECT statement with corresponding WHERE and ORDERBY clauses.

using System.Linq;
var countries = from c in _context.Countries
select c;
countries = countries.Where(c => c.Name.Contains("Russia"));
countries = countries.Where(c => c.ContinentID == 3);
countries = countries.OrderBy(c => c.Name);
List<Country> Countries = await countries.ToListAsync();

DisplayNameFor Helper

The @Html.DisplayNameFor() tag helper is used to display the friendly name for a property in a database model. By default, this will match the property name. If a [Display(Name = "Code")] annotation is applied to the property in the model class, that string is used instead

// Example database model
public class Continent
{
[Display(Name = "Code")]
public int ID { get; set; }
}
<!-- In .cshtml file -->
<div>
@Html.DisplayNameFor(model => model.Continent.ID)
</div>
<!-- Rendered HTML in browser -->
<div>
Code
</div>

Learn more on Codecademy

  • Learn how to build fast, secure, and maintainable web apps with ASP.NET and the Razor Pages architecture.
    • With Certificate
    • Intermediate.
      17 hours
  • Jumpstart your career with this skill path, first by learning the C# language, then building web apps with ASP.NET Core and the Razor Pages.
    • Includes 7 Courses
    • With Certificate
    • Intermediate.
      41 hours