What is the reason for using Dbmigration in Codefirst?

Asked

Viewed 221 times

5

What is the goal of using Dbmigration when developing a project using Codefirst? Using it is a good practice, or is something that does not cause major impacts on the implementation and/or maintenance of the system?

2 answers

4


What Dbmigration?

Represents the base class for code-based migrations. Entity Framework Migrations Apis are not designed to accept input provided by unreliable sources (as the end user of an application). If the input is accepted from such sources that must be validated before being passed to these Apis to protect against SQL injection attacks, etc. (MSDN Microsoft, Dbmigration Class. 2014. Available at: http://msdn.microsoft.com/en-us/library/system.data.entity.migrations.dbmigration(v=vs.113). aspx. Accessed: 22.Jun.2014, google website translation)

In addition to the trivial functionality of modifications to your Entities, it has a protective character as reported in translation above. When you design something new, and begin its development by the entity classes, Dbmigration takes responsibility for making these changes and protecting your end-user code. This is important through invasions and the famous SQL injection attacks.

Goal:

The main objective is the changes that your project is requesting during the programming, from a simple addition of a property, a collection, to the addition of foreign, primary and current keys 6+ indexes.

Example:

You started your model by a class Carro as model presenting 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 he created his class Db who 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 do not have the base created nor the table, so how should I proceed with this creation of the bank and the respective table.

In the Package Manager Console type: enable-migrations and press Enter

inserir a descrição da imagem aqui

A file will be created inside the folder Migrations by the name of Configuration.

internal sealed class Configuration : DbMigrationsConfiguration<ConsoleApplication6.Db>
{
    public Configuration()
    {
        //AutomaticMigrationsEnabled = false;
            AutomaticMigrationsEnabled = true;
    }    
    protected override void Seed(ConsoleApplication6.Db context) { }
}

Note that the configuration AutomaticMigrationsEnabled = false; place AutomaticMigrationsEnabled = true; so that modifications to its base can be made Go back again Package Manager Console and type add-Migration and a name any example

add-migration newdb

inserir a descrição da imagem aqui

And with it 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 yet had the generation of the physical model (the base and the table) we only have a conceptual model. How to proceed:

Again to Package Manager Console and type: update-database and press Enter

inserir a descrição da imagem aqui

When showing no error on the screen, and appear this message:

Applying explicit migrations: [201406221524303_newdb].
Applying explicit migration: 201406221524303_newdb.
Running Seed method.

Your seat and Cars table as shown below:

inserir a descrição da imagem aqui

Good so far so good, but now we want to add an extra field in this class Cars to keep her 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 I change at the base or by the code?

Now it’s all about the code, we do the next steps

add-migrations newcodigo

he will create another aquivo 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");
    }
}

note that it is the addition of a new Columa with the name Year equal was proposed in the conceptual model and to confirm the changes type:

update-database

and press Enter its base stays like this:

inserir a descrição da imagem aqui

Good practice:

It is essential for the reason, CodeFirst and does not get stuck in Database Management Systems (DBMS) technology, bringing the comfort of coding only in Visual Studio.

  • 1

    Is there a time when it is necessary to change the Dbmigration code generated automatically by the Entity Framework?

  • 1

    No... I never needed hair

2

What is the purpose of using DbMigration when a project is being developed using Code First?

The objectives are not to technologically depend on a database and not to manually control the history of modifications of that database.

When developing your application, creating, modifying or excluding Models, the framework is responsible for generating the changes that will be necessary in the database for the system to work. The goal is to leave the development as agnostic as possible regarding the database.

Using it is a good practice, or is something that does not cause major impacts on the implementation and/or maintenance of the system?

Yes, it is an excellent practice, precisely because it removes the responsibility of the developer of having to update the database every time the application code is modified.

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.

In the implementation, it is recommended to use the automatic migrations configuration, since the Models changes all the time. Already when the system is published in production, the recommended configuration is manual migrations, with the most controlled code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.