adc90
adc90

Reputation: 303

Using Entity Framework to refactor database

I'm working with an older database that we'd like to make some changes to. I've been reading about the fluent API which I like, however the more I read through it the more it seems like that has to be approached from a code first perspective. What I'd like to know is, is there any way to utilize the fluent API when you have the database first? Some things I'm looking to do would be for example refactor some column names on the database side and have them mapped to the existing data model, so that I can change them gradually throughout the application. I'm wondering if anyone has had any experience doing this and what would be the best place to start.

Upvotes: 1

Views: 665

Answers (1)

Michael buller
Michael buller

Reputation: 586

Entity Framework is an ORM between your application and your database. You can start model first, code first or database first and still use the features. If you are worried about what Entity Framework will do to your database, then you want to look into migrations. If migrations are configured to auto and to allow data loss, then you could lose data by making changes in your classes. If you manage it correctly though, you could use EF to model the database as is, then use the migrations to actually bring the database along. I will say that the Fluent API is really tailored to code first and doing the below will actually be more work than generating POCO from your database and just using the code. Either way, I hope this helps.

You are going to have to create a configuration that derives from EntityTypeConfiguration

So with your example,

public class CustomerConfiguration: EntityTypeConfiguration<Customer>;
{

    public CustomerConfiguration(): base()
    {

    HasKey(p => p.Id);
    Property(p => p.Id).
        HasColumnName("Id").
        HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).
        IsRequired();
    Property(p => p.dtUpdated).
        HasColumnName("EntryTs").
        IsRequired();
    ToTable("Customers");
    }

}

Or with fluent api... modelBuilder.Entity<ClassName>().ToTable("DatabaseTableName", "DatabaseSchema");

https://msdn.microsoft.com/en-us/library/jj591617(v=vs.113).aspx

Upvotes: 2

Related Questions