简体   繁体   中英

Mapping MySQL database tables/fields to C# entity classes manually

With version 4 of the Entity Framework, you have the option to doing what they call Code First. The thing is that the naming of your classes and fields/properties need to match the database from what I know. I am using MySQL and as such I use all lowercase and underscores in naming as capitalization is not supported on all OSes and can make MySQL act weird if you try to force it. The issue is that I use the standard C# naming conventions of using camelCase and PascalCase. Is there a way to map the naming in my database to my classes in C# without using the entity model designer (the .edmx file) as the design seems a bit buggy. Thanks.

You can use the overridable method OnModelCreating which will run on first instantiation of the class. There you can override individual tables like so

public class Context : DbContext {

    //your models

    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        modelBuilder.Entity<SomeTable>()
                         .MapSingleType()
                         .ToTable("YourTableNameInDatabase");
    }
}

It's that simple :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM