Reputation: 4008
I have an existing database. I was hoping there was a way to generate class files from this database. However, I seem to see a lot of generating the database from the class files.
Is there a way to generate class files from an existing database using the Entity Framework? If so how? Can someone point me to a tutorial?
Upvotes: 66
Views: 142461
Reputation: 686
EDMX model won't work with EF7 but I've found a Community/Professional product which seems to be very powerfull : http://www.devart.com/entitydeveloper/editions.html
Upvotes: 2
Reputation: 11
Upvotes: 1
Reputation: 9002
1) First you need to generate EDMX
model using your database. To do that you should add new item to your project:
ADO.NET Entity Data Model
from the Templates list. So now you have Model1.edmx
file in your project.
2) To generate classes using your model:
EDMX
model designer.EF 4.x DbContext Generator for C#
.Notice that two items are added to your project:
Model1.tt
(This template generates very simple POCO classes for each entity in your model) Model1.Context.tt
(This template generates a derived DbContext to use for querying and persisting data)3) Read/Write Data example:
var dbContext = new YourModelClass(); //class derived from DbContext
var contacts = from c in dbContext.Contacts select c; //read data
contacts.FirstOrDefault().FirstName = "Alex"; //edit data
dbContext.SaveChanges(); //save data to DB
Don't forget that you need 4.x version of EntityFramework. You can download EF 4.1 here: Entity Framework 4.1.
Upvotes: 124
Reputation: 9002
I found very nice solution. Microsoft released a beta version of Entity Framework Power Tools: Entity Framework Power Tools Beta 2
There you can generate POCO classes, derived DbContext and Code First mapping for an existing database in some clicks. It is very nice!
After installation some context menu options would be added to your Visual Studio.
Right-click on a C# project. Choose Entity Framework-> Reverse Engineer Code First (Generates POCO classes, derived DbContext and Code First mapping for an existing database):
Then choose your database and click OK. That's all! It is very easy.
Upvotes: 16