Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - Generating Classes

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?

like image 879
JavaScript Developer Avatar asked Apr 12 '12 15:04

JavaScript Developer


People also ask

How do you create a model class from a database?

Right-click the App_Data folder in the Solution Explorer window and select the menu option Add, New Item. From the Add New Item dialog box, select SQL Server Database, give the database the name MoviesDB. mdf, and click the Add button.

How do I create a model class in EDMX?

There is no automatically refresh the EDMX (it will be nice from MS if they implement that at some point) and the best and most accurate way to refresh the EDMX is by deleting all tables in the Diagram and then deleting all complex types etc. in the Model Browser.

What is EDMX file in Entity Framework?

edmx file is an XML file that defines an Entity Data Model (EDM), describes the target database schema, and defines the mapping between the EDM and the database. An . edmx file also contains information that is used by the ADO.NET Entity Data Model Designer (Entity Designer) to render a model graphically.


1 Answers

1) First you need to generate EDMX model using your database. To do that you should add new item to your project:

  • Select ADO.NET Entity Data Model from the Templates list.
  • On the Choose Model Contents page, select the Generate from Database option and click Next.
  • Choose your database.
  • On the Choose Your Database Objects page, check the Tables. Choose Views or Stored Procedures if you need.

So now you have Model1.edmx file in your project.

2) To generate classes using your model:

  • Open your EDMX model designer.
  • On the design surface Right Click –> Add Code Generation Item…
  • Select Online templates.
  • Select EF 4.x DbContext Generator for C#.
  • Click ‘Add’.

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.

like image 197
algreat Avatar answered Oct 11 '22 16:10

algreat