Now, we will update the database from Visual Studio PMC. Before updating, we need to map the entities model name with the database table name. In the below diagram, you can see that the table name is prefixed with schema name SalesLT.ProductModel but our entity name is ProductModel.
So, we have a concept called the Table attribute.
The Table attribute is applied to an entity to specify the name of the database table that the entity should map to. The above example specifies that the product model entity should map to a database table named SalesLT.ProductModel.
So, in the Attribute folder, we can add a DBTableAttribute class which inherits from TableArribute and take care of these conversions.
DBTableAttribute.cs
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations.Schema;
- using System.Text;
-
- namespace EFCoreSample.Attibute
- {
- [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
- public class DbTableAttribute : TableAttribute
- {
- public DbTableAttribute(string name) : base(GetTableName(name))
- {
- Schema = GetSchema(name);
- }
-
- private static string GetSchema(string name)
- {
- var split = name.Split('.');
-
- if (split.Length == 1)
- return null;
-
- return split[0];
- }
-
- private static string GetTableName(string name)
- {
- var split = name.Split('.');
-
- if (split.Length == 1)
- return split[0];
-
- return split[1];
- }
- }
- }
Adding the attribute to the ProductModel Entity : (present inside Entities Folder)
- using EFCoreSample.Attibute;
- using Microsoft.EntityFrameworkCore;
- using System;
- using System.Collections.Generic;
-
- namespace EFCoreSample.Entities
- {
- [DbTable("SalesLT.ProductModel")]
- public partial class ProductModel
- {
- public ProductModel()
- {
- Product = new HashSet<Product>();
- ProductModelProductDescription = new HashSet<ProductModelProductDescription>();
- }
Creating or Updating the Database
For updating the database, run the below command in Package Manager Console(PMC).
Update-DataBase
- The database command will create a database based on the context and domain classes and the migration snapshot.
- When we run the update-database command after creating the first migration, a table also gets created in Db (_EFMigrationHistory) which will store all the names of the migrations, as and when they get applied to the database.
Whenever we run the update database command, it will apply all the migrations to the database.
Thanks!
Sridhar YelagandhulaPosted Jan 26, 2019, 10:37 AM
Why we use migrations in Code first Approach ?