Welcome to the Data Annotations lesson! Today, we're going to explore an essential aspect of ASP.NET development that makes it easier to validate and manage data in your applications.
Data Annotations are attributes that you apply to properties in your classes to provide metadata for properties and methods. In ASP.NET, Data Annotations help with data validation, making it simple to ensure user input is correct before saving data to the database.
Before diving into Data Annotations, let's make sure you have the necessary tools installed:
Once you have those tools installed, let's create a new ASP.NET Core Web Application:
dotnet new webapp -o DataAnnotationsExample
cd DataAnnotationsExample
To start using Data Annotations, you'll need to include the Microsoft.EntityFrameworkCore.Annotation package in your project:
dotnet add package Microsoft.EntityFrameworkCore.Annotation
Now, let's create a new model class, Person, with some Data Annotations:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class Person
{
public int Id { get; set; }
[Required]
[StringLength(50)]
public string FirstName { get; set; }
[Required]
[StringLength(50)]
public string LastName { get; set; }
[Range(18, 100)]
public int Age { get; set; }
[ForeignKey("CountryId")]
public int CountryId { get; set; }
public Country Country { get; set; }
}In the example above, we've added several Data Annotations to the Person model:
Required ensures that the property (FirstName and LastName) has a value.StringLength limits the length of the string property (FirstName and LastName).Range validates that the property (Age) is within a specified range.ForeignKey indicates that the property (CountryId) is a foreign key.Let's create a simple example to demonstrate how Data Annotations work in a real-world application.
Country model:public class Country
{
public int Id { get; set; }
public string Name { get; set; }
}using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{ }
public DbSet<Person> People { get; set; }
public DbSet<Country> Countries { get; set; }
}Startup.cs file to configure the database context:public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}PersonsController:using Microsoft.AspNetCore.Mvc;
using System.Linq;
using DataAnnotationsExample.Data;
using DataAnnotationsExample.Models;
public class PersonsController : Controller
{
private readonly ApplicationDbContext _context;
public PersonsController(ApplicationDbContext context)
{
_context = context;
}
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create([Bind("FirstName, LastName, Age, CountryId")] Person person)
{
if (ModelState.IsValid)
{
_context.Add(person);
_context.SaveChanges();
return RedirectToAction(nameof(Index));
}
return View(person);
}
public IActionResult Index()
{
return View(_context.People.ToList());
}
}Now you can run the application and try to create a new person with invalid data (e.g., an empty first name or an age outside the range). The application will prevent the invalid data from being saved and show an error message, demonstrating the power of Data Annotations in ASP.NET.
That's it for our introduction to Data Annotations! Stay tuned for more in-depth lessons on ASP.NET. Happy coding! 🚀