Let's see how we can add additional validations using Entity Framework
Creating an Application
Connecting to a Database
Adding Validation
Add the 'IEntityTypeConfiguration' interface in the context class and implement the interface
After implementation, a method to configure will be added at the bottom (I moved it to the top manually)
▶ Adding Validations
We can use the property method to add validations to the entities and properties
builder.Property()
builder.Property(p => p.Description).HasMaxLength(200);
▶ Adding Types
We can use the property method to add types to the properties
builder.Property(d => d.Fee).HasColumnType("decimal(18,2)");
For instance, we can add a 'decimal' type to Sqlite which does not have the type.
※ Items that have a spanner icon are attributes
Override the 'OnModelCreating' method to use the configuration at the bottom
using System.Reflection;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}
※ We can have a separate folder to organize our files
Create a folder
Add a C# class
Add the interface and validation as shown above (Or move the configuration file if already have one. In this scenario, additional work might be needed depending on where the file was located)
Add the overriding 'OnModleCreating' method in the context file
In this writing, we have seen how we can add validations when creating a database in a .NET application
'Backend > .NET' 카테고리의 다른 글
Application Architecture - Generic Repository (0) | 2023.04.09 |
---|---|
Application Architecture - Repository with Service (0) | 2023.04.07 |
Application Architecture - Repository (0) | 2023.03.30 |
Application Architecture - MVC (0) | 2023.03.30 |
.NET - Cleaning Up Program File: Service Extension Method (0) | 2023.03.08 |