What is the purpose of using DbMigration when developing a project using CodeFirst? Is using it a good practice, or is it something that does not cause major impacts on the implementation and / or maintenance of the system?
What is the purpose of using DbMigration when developing a project using CodeFirst? Is using it a good practice, or is it something that does not cause major impacts on the implementation and / or maintenance of the system?
What DbMigration?
Represents the base class for code-based migrations. Entity Framework Migrations APIs are not designed to accept input from untrusted sources (such as the end user of an application). If the input is accepted from such sources they must be validated before being passed to these APIs to protect against SQL injection attacks, etc. ( Microsoft MSDN, DbMigration Class. 2014. Available at: #
In addition to the trivial functionality of modifications in their Entities, it has a protective character as reported in translation just above. When you design something new, and start developing it by entity classes, DbMigration assumes the responsibility of making those changes and protecting your end-user code. This is important through invasions and the famous SQL injection attacks.
Goal:
The main goal is the changes your project is requesting in the course of programming, from a simple addition of a property, a collection, to the addition of foreign keys, primary, and the current 6+ indexes.
Example:
You started your model with a Carro
class as the template below:
[Table("Carros")]
public class Carro
{
[Key]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int CarroId { get; set; }
[Required]
[MaxLength(100)]
public string Descricao { get; set; }
}
Soon after you've created your class Db
that inherits from DbContext
Entity Framework 6 + ):
public class Db : DbContext
{
public Db()
:base("Data Source=.\sqlexpress;Initial Catalog=cboNew0001;Persist Security Info=True;User ID=sa;Password=senha")
{ }
public DbSet<Carro> Carro { get; set; }
}
Well, until now we have not created the database nor the table, so how should I proceed with this creation of the database and its table?
In the Package Manager Console type: enable-migrations
and press Enter
AfilewillbecreatedinsidetheMigrationsfolderwiththenameofConfiguration
.
internalsealedclassConfiguration:DbMigrationsConfiguration<ConsoleApplication6.Db>{publicConfiguration(){//AutomaticMigrationsEnabled=false;AutomaticMigrationsEnabled=true;}protectedoverridevoidSeed(ConsoleApplication6.Dbcontext){}}
NotethattheAutomaticMigrationsEnabled=false;
settingplacesAutomaticMigrationsEnabled=true;
sothatyourbasemodificationsareenabledGobackagainPackageManagerConsoleandtypeadd-migrationandanameanyexample
add-migrationnewdb
And with this is created a class like this:
public partial class newdb : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Carros",
c => new
{
CarroId = c.Int(nullable: false, identity: true),
Descricao = c.String(nullable: false, maxLength: 100),
})
.PrimaryKey(t => t.CarroId);
}
public override void Down()
{
DropTable("dbo.Carros");
}
}
But, we have not had the generation of the physical model (the base and the table) we only have a conceptual model. How to proceed:
Again to the Package Manager Console and type: update-database
and press Enter
Whendisplayinganyerroronthescreen,andthismessageappears:
Applyingexplicitmigrations:[201406221524303_newdb].Applyingexplicitmigration:201406221524303_newdb.RunningSeedmethod.
YourbankandtheCarstablehavebeencreatedasshownbelow:
Well, that's fine, but now we want to add an extra field in this% car_to% Cars so that it looks like this:
[Table("Carros")]
public class Carro
{
[Key]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int CarroId { get; set; }
[Required]
[MaxLength(100)]
public string Descricao { get; set; }
//NEW CAMPO
public int? Ano { get; set; }
}
Where do I change the base or code?
Now it's all about the code, we take the next steps.
add-migrations newcodigo
it will create another one like this:
public partial class newcodigo : DbMigration
{
public override void Up()
{
AddColumn("dbo.Carros", "Ano", c => c.Int());
}
public override void Down()
{
DropColumn("dbo.Carros", "Ano");
}
}
Notice that it is the addition of a new column with the name of Year equal was proposed in the conceptual model and to confirm the changes type:
update-database
and press Enter your base looks like this:
Good practice:
It is essential for the reason, class
and does not get caught up in Database Management Systems (DBMS) technology, bringing the comfort of coding only in Visual Studio.
DbMigration
when developing a project using Code First? The goals are not to depend technically on a database and not to manually track the bank's change history.
When developing your application by creating, changing, or deleting Models , the framework is responsible for generating the changes that will be required in the database for the system to work. The goal is to make development as agnostic as possible for the database.
Yes, it's an excellent practice, just because it takes away the developer's responsibility to update the database every time the application code changes.
The maintenance of this database becomes trivial, since each Migration has the necessary modification instructions for the stage in which the system to be published is located.
In the implementation, it is recommended to use the automatic migration configuration, since the Models code changes all the time. Already when the system is published in production, the recommended configuration is manual migrations, with the code more controlled.