Round The Code

There are many helpful features in EF Core with migrations that you might not know about.

𝗘𝗻𝘁𝗶𝘁𝘆 𝘁𝘆𝗽𝗲 𝗰𝗼𝗻𝗳𝗶𝗴𝘂𝗿𝗮𝘁𝗶𝗼𝗻
You can override the OnModelCreating method in your DbContext to configure your entities.

But did you know that you can also create your own class for each entity configuration?

You'll need to implement the IEntityTypeConfiguration interface in the class passing in the entity as the generic type, and implement the Configure method to configure your entity.

To use it in your DbContext, you'll need to override the OnModelCreating method and call ApplyConfigurationsFromAssembly method from the ModelBuilder instance, loading the assembly where your entity configurations are stored.

𝗦𝗲𝗲𝗱 𝗱𝗮𝘁𝗮
This allows you to populate a database table with an initial set of data that is used across all environments.

You can call the HasData method inside the EntityTypeBuilder type when configuring an entity, and add the data you wish to be populated to the database.

𝗩𝗮𝗹𝘂𝗲 𝗰𝗼𝗻𝘃𝗲𝗿𝘁𝗲𝗿𝘀
This allows you to convert your data into a certain format when saved to the database. Then you convert it back when it's used in the application.

An example of this is saving a date and time in the database using the UTC timezone. You can then convert it back to the local timezone on the server when used in the application.

You can do this by creating a class and inheriting the ValueConverter type.

𝗥𝘂𝗻𝗻𝗶𝗻𝗴 𝗮 𝗦𝗤𝗟 𝗰𝗼𝗺𝗺𝗮𝗻𝗱
You can create an empty migration script in EF Core and in the MigrationBuilder type, you can call the Sql command to run a query when performing this migration.

An example of this is if you want to create a new column in a database table and populate it with an initial set of data based on the current record.

𝗪𝗮𝘁𝗰𝗵 𝗺𝘆 𝘃𝗶𝗱𝗲𝗼 𝘁𝗼 𝗳𝗶𝗻𝗱 𝗼𝘂𝘁 𝗺𝗼𝗿𝗲 𝗮𝗯𝗼𝘂𝘁 𝘁𝗵𝗲𝘀𝗲 𝗶𝗻𝘃𝗮𝗹𝘂𝗮𝗯𝗹𝗲 𝗳𝗲𝗮𝘁𝘂𝗿𝗲𝘀.

1 year ago | [YT] | 2