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

前端 未结 6 776
粉色の甜心
粉色の甜心 2021-02-06 03:04

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 nee

6条回答
  •  醉酒成梦
    2021-02-06 03:38

    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(null);
        }
    
        // DbSets here
        public DbSet 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().ToTable("db_PartTable");
        modelBuilder.Entity().Property(p => p.PartID) 
            .HasColumnName("Part_ID");
        modelBuilder.Entity().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

提交回复
热议问题