共用方式為


Code First Migrations: Alpha 3 Released

 


The information in this post is out of date.

Visit msdn.com/data/ef for the latest information on current and past releases of EF.

For Code First Migrations see https://msdn.com/data/jj591621


 

A couple of weeks ago we released Alpha 2 of Code First Migrations. Today we are happy to make Alpha 3 available to you.

The overall feedback we got on Alpha 2 was that you like the direction we are headed. We heard that there is definitely a use case for automatic migrations, and while not everyone will use them, we should continue to invest in them. You are asking us to look at the story for data migration that doesn’t involve dropping down to SQL. Alpha 2 also had some commonly encountered bugs that were annoying and we needed to fix

Alpha 3 is still is primarily focused on the developer experience inside of Visual Studio. This release adds most of development time features we plan to include in the first RTM. Your feedback will guide any changes we make to the overall design. Apart from responding to your feedback our team is starting to focus on improving quality. We are also working on completing the deployment and team-build stories, including a command line tool and an MSDeploy provider.

 

What Changed

Alpha 3 is focused on adding the remaining features that you have been asking for around development time migrations. The primary changes in Alpha 3 are:

  • VB.NET migration generation is now available.
  • Upgrade/Downgrade to any migration is now available via the –TargetMigration switch.
  • Seed data can now be added by overriding the Seed method of the Settings class. Data is expressed in terms of the current model and the Seed method is called after upgrading to the latest migration.
  • We removed TargetDatabase from the Settings class. Instead you can use the –TargetDatabase switch to specify the name of a connection string from your App/Web.config file.
  • You can now start using Code First Migrations against an existing database that was created by Code First. To do this issue an Update-Database command when you model is the same as the model that created the database. To use this feature the EdmMetadata table must be present in the database. This original creation of the database and tables will be counted as an automatic migration, if you want a code-based migration for the initial create of the database and tables you must drop the database and begin using migrations against an empty or non-existent database.
  • Improved error logging when an exception is encountered.
  • The bugs that required SQL Compact and SQL Express to be available are now resolved.

 

Known Issues

Some known issues, and ‘yet to be implemented’ features include:

  • Code-based migrations and databases generated with Alpha 2 cannot be used with Alpha 3. Because Alpha 2 was such an early release we needed to make some changes to the table we use to store migrations and the way we generate and identify code-based migrations. If you were using Alpha 2 you will need to regenerate migrations and run them to create your database. We realize this is painful but it is one of the trade-offs associated with getting previews into your hands early in the development process. We are making an effort to reduce such changes in future previews.
  • If you are updating the EntityFramework.Migrations package you will need to close and re-open Visual Studio after updating. This is required to reload the updated command assemblies.
  • No outside-of-Visual-Studio experience. Alpha 2 only includes the Visual Studio integrated experience. We also plan to deliver a command line tool and an MSDeploy provider for Code First Migrations.

 

Feedback

We really want your feedback on Code First Migrations. Is the solution we are delivering what you want? Are there features we should add? Please comment on this post with any feedback you might have.

 

Getting Started

There are two walkthroughs for Alpha 3, one focuses on the no-magic workflow that uses a code-based migration for every change. The other looks at using automatic migrations to avoid having lots of code in you project for simple changes.

Code First Migrations Alpha 3 is available via NuGet as the EntityFramework.Migrations package.

 

Prerequisites & Incompatibilities

Migrations is dependent on EF 4.1 Update 1, this updated release of EF 4.1 will be automatically installed when you install the EntityFramework.Migrations package.

Important: If you have previously run the EF 4.1 stand alone installer you will need to upgrade or remove the installation before using migrations. This is required because the installer adds the EF 4.1 assembly to the Global Assembly Cache (GAC) causing the original RTM version to be used at runtime rather than Update 1.

This release is incompatible with “Microsoft Data Services, Entity Framework, and SQL Server Tools for Data Framework June 2011 CTP”.

 

Support

This is a preview of features that will be available in future releases and is designed to allow you to provide feedback on the design of these features. It is not intended or licensed for use in production. If you need assistance we have an Entity Framework Pre-Release Forum.

 

ADO.NET Entity Framework Team

License.rtf

Comments

  • Anonymous
    September 21, 2011
    Have you fixed the team sharing problem?

  • Anonymous
    September 22, 2011
    Does Code First Migrations can work with other database (eg. Oracle)?

  • Anonymous
    September 22, 2011
    Still don't see how we control RI. No ON DELETE (CASCADE|SET DEFAULT|SET NULL|NO ACTION)? It seems as though the Fluid API to configure entities and relationships is not being supported. Is there plans to support this in the future? If not it seems to be a complete show stopper for me. Thanks, Sam

  • Anonymous
    September 22, 2011
    The comment has been removed

  • Anonymous
    September 22, 2011
    Could you please provide an example that uses seeding?

  • Anonymous
    September 22, 2011
    @Espen - Here you go: using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Providers; using System.Data.SqlClient; using GTG.Core.Entities; namespace GTG.Data.Migrations {    public class Settings : DbMigrationContext<GTGContext>    {        #region "Fields/Properties"        #endregion        #region "Constructor(s)"        public Settings()        {            AutomaticMigrationsEnabled = false;            SetCodeGenerator<CSharpMigrationCodeGenerator>();            AddSqlGenerator<SqlConnection, SqlServerMigrationSqlGenerator>();            // Uncomment the following line if you are using SQL Server Compact            // SQL Server Compact is available as the SqlServerCompact NuGet package            // AddSqlGenerator<System.Data.SqlServerCe.SqlCeConnection, SqlCeMigrationSqlGenerator>();        }        #endregion        #region "Methods"        protected override void Seed(GTGContext context)        {            base.Seed(context);            using (context)            {                // Categories                context.Categories.Add(new Category() { Name = "Chocolate", Display = true, DisplayIndex = 0 });                context.Categories.Add(new Category() { Name = "Flavors", Display = true, DisplayIndex = 1 });                context.SaveChanges();            }        }        #endregion    } }

  • Anonymous
    September 22, 2011
    @Stefan: yes, all you have to do is add code like this in App_Start:            var dbMigrator = new DbMigrator(new Settings());            dbMigrator.Update(); This will run whatever migrations are needed to bring your database up to date.

  • Anonymous
    September 22, 2011
    Will there be a way to migrate the database changes using the GUI, perhaps right-clicking on the solution name and using an UpdateDatabase choice, or maybe doing the same on the AppData folder?

  • Anonymous
    September 22, 2011
    @Slawek: Not directly, but there is a provider model for SQL generation that allows third-party databases to be supported. See  System.Data.Entity.Migrations.Providers.DbMigrationSqlGenerator

  • Anonymous
    September 22, 2011
    @Sam, Alpha 3 supports cascade delete. See the AddForeignKey API and the ForeignKey method that chains of the CreateTable method.

  • Anonymous
    September 22, 2011
    @Andrew J Peters - This is AWESOME!!! Man this is so great. I love this product!

  • Anonymous
    September 22, 2011
    @Matthew, Yes, we are building an MSDeploy provider that will integrate with the right-click->Publish workflow in VS.

  • Anonymous
    September 22, 2011
    @Andrew J Peters - So take this snippet from a migration code file, and assuming a "Customer" has many "Shipping Addresses", you would set this foreign key to cascade on delete to get rid of all the shipping addresses this customer owns? CreateTable(                "ShippingAddresses",                c => new                    {                        ID = c.Int(nullable: false, identity: true),                        CustomerID = c.Int(nullable: false),                        Name = c.String(nullable: false, maxLength: 100),                        Line1 = c.String(nullable: false, maxLength: 100),                        Line2 = c.String(maxLength: 100),                        Line3 = c.String(maxLength: 100),                        Line4 = c.String(maxLength: 100),                        Line5 = c.String(maxLength: 100),                        City = c.String(nullable: false, maxLength: 100),                        State = c.String(nullable: false, maxLength: 100),                        ZipCode = c.String(nullable: false, maxLength: 50),                        Country = c.String(nullable: false, maxLength: 150),                    })                .PrimaryKey(t => t.ID)                .ForeignKey("Customers", t => t.CustomerID, true);

  • Anonymous
    September 22, 2011
    @Sam, Yes. Specifying "casadeDelete: true" is more idiomatic as it is more descriptive.

  • Anonymous
    September 23, 2011
    The comment has been removed

  • Anonymous
    September 23, 2011
    @Solmead, Make sure you change your app.config connection string to point to Sql CE?

  • Anonymous
    September 23, 2011
    The comment has been removed

  • Anonymous
    September 24, 2011
    Yes, please keep automatic migrations.  As a start-up web developer, I don't care how you do it, just make the database match my models.

  • Anonymous
    September 26, 2011
    The comment has been removed

  • Anonymous
    September 26, 2011
    @EntityFramework Team, Excellent work! A round of drinks! Any timeline for Release Version?

  • Anonymous
    September 26, 2011
    The comment has been removed

  • Anonymous
    September 28, 2011
    The comment has been removed

  • Anonymous
    September 28, 2011
    think we may have found another SQLEXPRESS dependency problem... please take a look at my post here: social.msdn.microsoft.com/.../b608ce95-aa02-45fa-bc27-b7ce74007656

  • Anonymous
    September 29, 2011
    Does the "HasMany" and "HasRequired" Fluent API methods of the EntityTypeConfiguration class have any effect over the migrations? Or do all FK relationships get setup by properties on the objects now and then you can set the cascadeOnDelete property on the entity in the migration? Seems to output the same SQL with or without.

  • Anonymous
    September 29, 2011
    @Kris444, we will have a console runner in a future release. I believe NuGet will also work with Visual Web Developer Express so you could try that.

  • Anonymous
    September 29, 2011
    @Sam, Those APIs control the shape of your underlying EDM model, which is what Migrations uses to do things like scaffolding and Auto migrations. By default, when scaffolding migrations, we will add a cascadeDelete: true to scaffolded ForeignKey() or AddForeignKey() calls if the Association in the underlying EDM model has it specified.

  • Anonymous
    September 29, 2011
    @Andrew - So if I am using Code First, this does not apply?

  • Anonymous
    September 29, 2011
    The comment has been removed

  • Anonymous
    September 29, 2011
    @Andrew - My model is agnostic of the ORM/Data Layer, it cares nothing about how it gets persisted. With that said, I don't want to pollute the model with EF specific attributes. That is why I thought the EntityConfiguration Fluent API was neat, it gave me a way to control the model in a EF specific way. I can confirm that only parts of the Fluent API have an effect on migrations, such as "HasMaxLength" and "IsRequired/IsOptional". "HasMany.WithRequired" and vice versa do not have any effect on the migration in my experience. Am I missing something here? Thank! Sam

  • Anonymous
    September 29, 2011
    @Sam It is fine to use the Fluent API over annotations. The two are interchangeable. HasMany/WithRequired can affect a couple of things:

  1. Whether or not the generated FK column is nullable.
  2. If WillCascadeOnDelete is specified, then the DB FK will get cascade delete. Cheers, Andrew.
  • Anonymous
    September 29, 2011
    @Andrew - So with migrations, Cascade Deletes are off by default? Where as with the DBInitializer, they were on by default, is that correct? Thanks for all the clarification. Sam

  • Anonymous
    September 29, 2011
    @Andrew - So this on the EntityConfiguration for StockLine: HasRequired(x => x.ChildProduct).WithMany(x => x.StockLines).HasForeignKey(x => x.ChildProductID).WillCascadeOnDelete(); Should put a cascadeDelete: true on the migration correct? I get this: CreateTable(                "StockLines",                c => new                    {                        ID = c.Int(nullable: false, identity: true),                        ChildProductID = c.Int(nullable: false),                    })                .PrimaryKey(t => t.ID)                .ForeignKey("ChildProducts", t => t.ChildProductID); No cascadeDelete: true? I am a little confused. Sam

  • Anonymous
    September 29, 2011
    @Sam, I think I found the problem. There is a bug in our scaffold code generator where we are not correctly generating "cascadeDelete: false" for the CreateTable().ForeignKey() API. For now, you will need to manually edit the generated migration and add the missing cascadeDelete parameter. Sorry about that, Andrew.

  • Anonymous
    September 29, 2011
    The comment has been removed

  • Anonymous
    October 03, 2011
    @Andrew - Any idea when you guys will have a fix for the whole cascadeDelete issue?

  • Anonymous
    October 03, 2011
    @Sam, in the next release. For now it is easy to workaround by manually adding in the cascadeDelete parameter.

  • Anonymous
    October 05, 2011
    Are you planning to enable the use of protected/internal properties in Code First? Currently if I set a property as protected then it gets ignored. I know about the [InternalsVisibleTo] attribute but I don't want to configure every property in my project - that defeats the purpose of using Code First. Thanks, Ben

  • Anonymous
    October 05, 2011
    @Ben, non-public properties work now, it's just that they aren't included in your model by default. To include them they need to be registered with the DbModelBuilder using the fluent API. Because they aren't public, it can be more difficult to refer to them from configuration code. One approach is to nest a derived  EntityConfiguration class inside the Entity and configure that way. Another is to create static readonly Expression fields in the Entity that refer to the non-public properties -  the static fields can then be used in place of the actual properties in fluent API calls.

  • Anonymous
    November 02, 2011
    I have been using alpha3 for a couple of months and a consistent problem occurs. I have multiple projects all accessing the same database. When I use Update-Database or Add-Migration on more than the same project in any one session of Visual Studio Web Developer 2010 Express I get the last project's migration added to the current project's migration as a drop in the Up method and as create in Down method. I have to remove the config string from the project, do an Add-Migration, edit the migration to remove the inappropriate source, add the connection string and then call Update-Database. I have not seen anyone else mention this. I think it started after updating NuGet to the newest version but am not certain.

  • Anonymous
    November 16, 2011
    I am using code first migrations alpha 3 with my mvc project. I must say that i was really looking forward to Migrations since I started using MVC and Codefirst last January. Well done guys!! Migrations is working fine, when I run update-database the first time it is creating a new database called BillingEngine.Models.BillingEngineContext instead of BillingEngine as previously without migrations. Any further updated are then performed on the BillingEngine.Models.BillingEngineContext database. Please note that BillingEngine.Models is a namespace and BillingEngineContext is the class inheriting DBcontext, which is contained in the mentioned namespace. Can I use the API to specify the name of the database somewhere?. I would work if update the connection stings to use the new name but its a bit messy and too long a name. Thanks

  • Anonymous
    November 28, 2011
    Great job so far, guys, but please change the way the migration scripts are generated. The script generator doesn't specify a default PK constraint name in the generated CREATE TABLE statement. When you don't specify the primary key constraint name, SQL Server creates a cryptic one for you like: PK__User__1788CCAC27F8EE98 In the table designer in SSMS, the convention for the default PK name is as follows: PK_{table name} Please make the script generator specify the primary key constraint name by default using the SSMS naming convention, and optionally add the ability to override this default constraint name by adding an overload to the TableBuilder.PrimaryKey() method that allows for passing a constraint name argument. The script generator does happen to specify a foreign key constraint name in the generated script. However, the naming convention is as follows: FK_{child table name}{parent table name}{column name} The designers in SSMS create FK constraint names with this convention: FK_{child table name}_{parent table nae Please make the script generator follow the same convention as SSMS, and optionally add an overload to the TableBuilder.ForeignKey() method that allows specifying the constraint name as described above for the TableBuilder.PrimaryKey() method. Thanks!

  • Anonymous
    November 28, 2011
    My comment got mangled. The comment above should read: ... The designers in SSMS create FK constraint names with this convention: FK_{child table name}_{parent table name} ...

  • Anonymous
    November 29, 2011
    Is there a way to set a default value for a datetime column to "(getdate())"?

  • Anonymous
    April 22, 2012
    I did some digging and found how to programmatically mimic the "Update-Database" cmdlet. A lot of people were looking for this, so I threw it into my blog.  Here's the URL: joshmouch.wordpress.com/.../entity-framework-code-first-migrations-executing-migrations-using-code-not-powershell-commands

  • Anonymous
    April 23, 2012
    @Joshua R. Mouch - There is also some more information on using migrations from code here; romiller.com/.../running-scripting-migrations-from-code