问题
I have an existing database table Movie
. Now I want to write a POCO Movie.cs
which will map to that table. I want to have control over the mapping partially because I'm trying to learn more about EF.
The Movie
table has 3 fields: Title VARCHAR(255,), ReleaseDate DATETIME, Price MONEY
. What would my DbContext - derived class look like for this?
Coming from a Java/Hibernate background, I figured I would just map fields in the POCO to cols in the table, but it doesn't seem that straight forward in EntityFramework.
I only seem to find these 2 options:
"Code First" -> write everything in C#, then let EntityFramework generate and run migrations to constantly update and seed the DB.
"Database First" -> create the DB, then create a DB project in VS and generate an EDMX file which generates the POCO's for you
Both seem overly obtuse for the goal of mapping a single POCO to a single table. What am I missing? I've heard reference to "Fluent API," but that seems to lead me back to 1. or 2.
I struggled to find anything consistent in the docs that described what I was looking for.
回答1:
You have another option. You can write POCO class, map the class and disable migrations (migration involves also a metadata table called __MigrationHistory that you don't have in your database).
The class could be (using attributes to map the fields, you can use fluent interface as well)
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
}
For disable the migration and the model checking I usually set it in the context class (i.e. 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 Database. EF generates the POCO classes starting from database. Classes often need a refactoring but is still better than writing classes from scratch.
来源:https://stackoverflow.com/questions/34245935/manually-map-poco-to-existing-table-using-entity-framework