Is there an alternative to Code First Migrations with EF when all code changes are done by a DBA?

entity-framework

Question

I've read about Code First Migrations but it seems that this is not really suited to the Enterprise.

We have a DBA that does all our Database changes and we don't need to have these changes put into Classes and have database migration performed by the application.

If we change our classes and our fluent API and then have our DBA make changes to the database then how can we sync to our EF model? How is this normally done for Enterprise size applications?

1
9
3/15/2013 12:26:23 AM

Accepted Answer

Usually in such cases people use Database First approach.

Writing entities code manually when someone already designed database for you and when you can generate or update the model with several clicks just makes no sense. Of course, Code First could be convenient if your team is familiar with some other ORM where it was main approach and is not quite familiar with Entity Framework yet, or if your team is extremely small and nobody can write SQL script, but if you have skilled DBA, why you could need Code First?

2
3/15/2013 11:17:56 AM

Popular Answer

To me it doesn't seem like these other answers are sufficient.

You can turn off the EF initializer:

public ApplicationContext : DbContext
{
    public ApplicationContext()
        : base("ConnectionStringName")
    {
        Database.SetInitializer<ApplicationContext>(null);
    }

    // DbSets here
    public DbSet<Part> Parts {get; set;}

    // override OnModelCreating below ...
}

And then use Fluent API / data annotations however you normally would to setup your POCOs/models to match the existing DB.

Details at this blog: http://cpratt.co/entity-framework-code-first-with-existing-database/

In case that URL does not work in the future - here's what I mean:

After having set the Initializer off above, configure your POCO's that correspond to a table:

public class Part
{
    public string PartID {get; set;}
    public string Description {get; set;}
    public decimal Weightlbs {get; set;}
    public decimal Price {get; set;}
}

Then map your POCO to the existing DB table by overriding this method in your Application Context class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // Code First will assume a lot, but if you need to override things:

    modelBuilder.Entity<Part>().ToTable("db_PartTable");
    modelBuilder.Entity<Part>().Property(p => p.PartID) 
        .HasColumnName("Part_ID");
    modelBuilder.Entity<Part>().Property(p => p.Description)
        .HasMaxLength(100)
}

Another good blog for this, by Scott Guthrie: http://weblogs.asp.net/scottgu/using-ef-code-first-with-an-existing-database



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow