Let's see how we can add additional validations using Entity Framework
Creating an Application
How to create .NET web-API
Setting up development tools When working with .NET, we need tools to create a web application. We can download them in the link below.다. .NET | Free. Cross-platform. Open Source. (microsoft.com) .NET | Free. Cross-platform. Open Source. .NET is a develo
jin-co.tistory.com
Connecting to a Database
Working with SQLite in .NET (Code first)
There are two ways of using the Entity Framework to connect a database to a project. One way is to create the database first which is called the database first approach and the other, of course, is to write code first which is called the code first approac
jin-co.tistory.com
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 |