Manually map POCO to existing table using Entity Framework

I have an existing database table Movie

. Now I want to write a POCO Movie.cs

that will appear in this table. I want to have partial control over the display because I am trying to learn more about EF.

The table Movie

has three fields: Title VARCHAR(255,), ReleaseDate DATETIME, Price MONEY

. What would be my DbContext based class?

Coming from a Java / Hibernate background, I figured I would just map fields in POCO to cols in a table, but that doesn't seem straight forward in EntityFramework.

Only these 2 options seem to me:

  • "Code First" -> write everything in C # and then the EntityFramework generate and run migrations for continuous update and DB seed.

  • "Database first" -> create a db, then create a db project in VS and create an EDMX file that generates a POCO for you

Both seem too dumb for the purpose of mapping one POCO to one table. What am I missing? I heard a link to "Fluent API" but that seems to lead me to 1. or 2.

I tried my best to find in the docs everything that was described in the docs that described what I was looking for.

+1


source to share


1 answer


You have another option. You can write a POCO class, map the class and disable migration (the migration also includes a metadata table named __MigrationHistory, which you don't have in your database).

The class can be (using attributes to map fields, you can also use a fluent interface)

class Movie {
    [PrimaryKey]
    [MaxLength(255)
    public string Title {get; set;}
    public datetime ReleaseDate {get; set;}
    public float Price {get; set;} // Or the type you prefere
}

      



To disable migrations and model validation, I usually set it in the context class (i.e. the MyContext class).

class MyContext : DbContext {

    static MyContext()
    {
        System.Data.Entity.Database.SetInitializer<CloseUpContext>(null); // This disables model checking
    }

    public DbSet<Movie> Movies {get; set;}


}

      

An interesting feature is CodeFirst from the database. EF generates POCO classes starting from the database. Classes often need refactoring, but are still better than writing classes from scratch.

+3


source







All Articles