简体   繁体   中英

Using entity framework 4.1 Code-First on existing MySQL database

I'm trying to use the code-first approach with a MySQL db.

The kicker here, is that I can't drop and create the DB (on my hosting company) so I can't automagically create the tables in the database. I've looked at http://nuget.org/List/Packages/EFCodeFirst.CreateTablesOnly and Entity Framework CTP 4 - Code First Custom Database Initializer but I can't seem to get that to work with my MySQL.

Edit: Basically I'm looking for a solution that works like the above - by ONLY dropping and creating tables, and not the database itself, with MySQL.

Has anyone had any luck with this approach?

Thanks

This isn't what you asked for directly, but it might give you similar results.

You might try creating the database from scratch with your code-first approach, then take a diff between your fresh DB and the production DB to create migration scripts. These migration scripts could be executed in production without dropping your tables.

I know this ends up being a low-tech approach, but it could work for your scenario. The migration script approach is exactly how a lot of real companies do DB migrations/promotions to more restricted environments.

If you have a good idea of the types of changes you're going to make to your DB, then you could look for a code-first-ish solution for migration scripts that isn't EF specific. Something like Sharp Migrations , or one of many similar tools .

I am using code first with an existing database. All you need to do is set your connectionstring in the web.config like the following.

NOTE:- Yours might vary because u use MySQL.

<connectionStrings>
<add name="PriceCompareEntity"
     connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\PriceCompare.mdf;User Instance=true"
     providerName="System.Data.SqlClient" />
</connectionStrings>

Then just make sure that your model classes matches the tables in database. Database aren't dropped and created on fly, unless its told too, like in the following case i am asking the EF to create the database in Global.asax

System.Data.Entity.Database.SetInitializer(new MvcMusicStore.Models.SampleData());

For more information, you can visit EF Code first with Existing DB

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